如何将用户输入数字的数字打印为单词?例如,假设我输入一个数字123
然后我想要一行"一二三"打印。
以下是我的尝试:
#include<stdio.h>
int main()
{
int i=0,a,c,o=0,p;
printf("enter the number you want ");
scanf("%d",&a);
c=a;
while(a !=0)
{
a=a/10;
i++;
}
while(o<=i)
{
p=c%10;
c=c/10;
if(p==1)
printf(" one ");
else if(p==2)
printf(" two ");
else if(p==3)
printf(" three ");
else if(p==4)
printf(" four ");
else if(p==5)
printf(" five ");
else if(p==6)
printf(" six ");
else if(p==7)
printf(" seven ");
else if(p==8)
printf(" eight " );
else if(p==9)
printf(" nine ");
else if(p==0)
printf(" zero ");
o++;
}
return 0;
}
打印额外零。我该如何解决这个问题?
答案 0 :(得分:0)
额外零点来自这里:
while(o<=i)
i
是位数。由于o
从0开始,因此范围从0到i
,因此您需要多一次循环。那时,c
为0,这就是打印的内容。
您可以通过更改条件来解决此问题:
while(o<i)
然而,还有另一个问题。该程序以相反的顺序打印单词。您可以通过保存数组中的数字,然后在该数组中向后循环以打印数字来解决此问题。
#include<stdio.h>
int main()
{
int i=0,a,p;
int digits[25]; // enough for a 64-bit number
// list of digits names that can be indexed easily
char *numberStr[] = { " zero ", " one ", " two ", " three ", " four ",
" five ", " six ", " seven ", " eight ", " nine " };
printf("enter the number you want ");
scanf("%d",&a);
while(a !=0)
{
// save each digit in the array
digits[i] = a%10;
a=a/10;
i++;
}
i--; // back off i to contain the index of the highest order digit
// loop through the array in reverse
while(i>=0)
{
p=digits[i];
printf("%s", numberStr[i]);
i--;
}
return 0;
}