今天一刚开始学c的mm问我一道题目,给一个不多于5位的正整数,要求:1.求出它是几位数;2.分别打印出每一位数字;3.按逆序打印出各位数字。
偶马上写出来程序,但是用劲毕生所学才讲的使mm明白,晕!~
程序如下:
#include <stdio.h>
int main()
{
long int number;
int n,a,b,c,d,e; /*a,b,c,d,e分别代表这个不超过5位正整数的万,千,百,十,个位*/
printf("please input a number:");
scanf("%ld",&number);
/*求出输入的数是几位数*/
if(number>=10000){n=5;printf("the number has %d bits\n",n);}
else if(number>=1000){n=4;printf("the number has %d bits\n",n);}
else if(number>=100){n=3;printf("the number has %d bits\n",n);}
else if(number>=10){n=2;printf("the number has %d bits\n",n);}
else {n=1;printf("the number has %d bits\n",n);}
/*分别打印每一位数字*/
switch(n)
{
case 5:a=number/10000;
b=number%10000/1000;
c=number%10000%1000/100;
d=number%10000%1000%100/10;
e=number%10000%1000%100%10;
printf("%d,%d,%d,%d,%d\n",a,b,c,d,e);
break;
case 4:b=number/1000;
c=number%1000/100;
d=number%1000%100/10;
e=number%1000%100%10;
printf("%d,%d,%d,%d\n",b,c,d,e);
break;
case 3:c=number/100;
d=number%100/10;
e=number%100%10;
printf("%d,%d,%d\n",c,d,e);
break;
case 2:d=number/10;
e=number%10;
printf("%d,%d\n",d,e);
break;
default: e=number;printf("%d\n",e);
}
/*按逆序打印出各位数字*/
switch(n)
{
case 5:number=e*10000+d*1000+c*100+b*10+a;
printf("%ld\n",number);break;
case 4:number=e*1000+d*100+c*10+b;
printf("%ld\n",number);break;
case 3:number=e*100+d*10+c;
printf("%ld\n",number);break;
case 2:number=e*10+d;
printf("%ld\n",number);break;
default: printf("%d\n",e);
}
return 0;
}
本程序在xp+vc6.0下编译通过。