C Exercise Example 29
Title:Given a positive integer with no more than 5 digits, requirements: 1. Find how many digits it has; 2. Print each digit in reverse order.
Program analysis:Learn to decompose each digit, as explained below.
Example
// Created by www.example.com on 15/11/9.
// Copyright © 2015 Example. All rights reserved.
//
#include <stdio.h>
int main( )
{
long a,b,c,d,e,x;
printf("Please enter a 5-digit number:");
scanf("%ld",&x);
a=x/10000; /*Extract the ten-thousands digit*/
b=x%10000/1000; /*Extract the thousands digit*/
c=x%1000/100; /*Extract the hundreds digit*/
d=x%100/10; /*Extract the tens digit*/
e=x%10; /*Extract the ones digit*/
if (a!=0){
printf("It is a 5-digit number, in reverse order: %ld %ld %ld %ld %ld\n",e,d,c,b,a);
} else if(b!=0) {
printf("It is a 4-digit number, in reverse order: %ld %ld %ld %ld\n",e,d,c,b);
} else if(c!=0) {
printf("It is a 3-digit number, in reverse order: %ld %ld %ld\n",e,d,c);
} else if(d!=0) {
printf("It is a 2-digit number, in reverse order: %ld %ld\n",e,d);
} else if(e!=0) {
printf("It is a 1-digit number, in reverse order: %ld\n",e);
}
}
The output result of the above example is:
请输入 5 位数字:12345 为 5 位数,逆序为: 5 4 3 2 1other extensions