我用 C 语言编写了一个程序,它打印表示输入数字(逐位)的英文,例如,当您输入 时938
,它会打印出nine three eight
当输入太大(超过 9 位)时它不起作用。谁能向我解释为什么会这样?我尝试使用 unsigned int 而不是 int 作为变量,但它仍然不起作用。
#include <stdio.h>
/**
10/17/2012
Programming in C
Ch6 no. 6
Program doesn't work when number gets too large (>9 digits)
Print english that represents input number (digit by digit)
*/
int main(void){
int digit;//use to hold digit
int number;//hold input number
int revNumber = 0; //the reversed digit of the input number
int no_zero = 0;//number of zero needed to be printed at the end
int i = 1;//hold how many digits does the number have (+1 = i*10)
printf("Please enter a number\n");
scanf("%u", &number);
int testing = number;//a copy of input number for
//counts how many digits does the number have (+1 = i*10)
for(; testing != 0;i *= 10){
testing /= 10;
}
//make the reversed number
do{
i /= 10;
digit = number % 10;
if(digit == 0)
no_zero++;
revNumber += (digit*i);
number /= 10;
}while(number != 0);
//print the result using the reversed number
do{
digit = revNumber % 10;
revNumber /= 10;
switch(digit)
{
case 0:
printf("zero ");
no_zero--; //minus zero not at the end
break;
case 1:
printf("one ");
break;
case 2:
printf("two ");
break;
case 3:
printf("three ");
break;
case 4:
printf("four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("six ");
break;
case 7:
printf("seven ");
break;
case 8:
printf("eight ");
break;
default:
printf("nine ");
}
}while(revNumber != 0);
//add back the ending zero
for(;no_zero!=0;no_zero--)
printf("zero ");
return 0;
}