输入一个不超过 5 位数的数字,按照要求,输出这个数字的相关属性。(谭浩强 C 语言 第三版 112 页第 5.7 题)
给一个不多于 5 位的正整数,要求:
因为数字的范围已经限定死,所以我们可以让数字跟每个范围内的数字的最大值比较,比如 999,99 。要求输出每一位数字的话,只需要跟 100,10 这些数字相除就可以了,倒序输出的话,将上面算出的数字反方向相乘。
#include <stdio.h>
void main()
{
printf("嗨客网(www.haicoder.net)\n\n");
long int num;
int indiv,ten,hundred,thousand,ten_thousand,place; //分别表示 个,十,百,千,万,和几位数
printf("请输入一个整数(0~99999):");
scanf("%ld",&num);
while(num > 99999 || num < 0)
{
printf("请输入一个整数(0~99999):");
scanf("%ld",&num);
}
if(num > 9999)
{
place = 5;
}
else if(num > 999)
{
place = 4;
}
else if (num > 99)
{
place = 3;
}
else if(num > 9)
{
place = 2;
}
else
{
place = 1;
}
printf("位数 = %d",place);
printf("\n每位数字为: ");
ten_thousand = num/10000;
thousand = (int)(num - ten_thousand * 10000 ) / 1000;
hundred = (int)(num - ten_thousand * 10000 - thousand * 1000 ) / 100;
ten = (int)(num - ten_thousand * 10000 - thousand * 1000 - hundred * 100 ) / 10;
indiv = (int)(num - ten_thousand * 10000 - thousand * 1000 - hundred * 100 - ten*10);
switch(place)
{
case 5 :
printf("%d,%d,%d,%d,%d",ten_thousand,thousand,hundred,ten,indiv);
printf("\n反序数字为 : ");
printf("%d%d%d%d%d",indiv,ten,hundred,thousand,ten_thousand);
break;
case 4 :
printf("%d,%d,%d,%d",thousand,hundred,ten,indiv);
printf("\n反序数字为 : ");
printf("%d%d%d%d",indiv,ten,hundred,thousand);
break;
case 3 :
printf("%d,%d,%d",hundred,ten,indiv);
printf("\n反序数字为 : ");
printf("%d%d%d",indiv,ten,hundred);
break;
case 2 :
printf("%d,%d",ten,indiv);
printf("\n反序数字为 : ");
printf("%d%d%",indiv,ten);
break;
case 1 :
printf("%d",indiv);
printf("\n反序数字为 : ");
printf("%d",indiv);
break;
}
}
运行后,控制台输出如下:
首先按照题目要求,我们输入一个 1~5 位的数字,我们可以将数字与每一个位数区间里面的最大值进行比较,然后得出这个数字的位数。拿到数字的位数后,我们可以利用与整 10 倍数的数据相除得到每位的数字。