如何在拼写中打印数字?

How to print a number in spellings?

所以我在这里尝试编写一个代码,将数字转换为其拼写格式。例如,用户输入任何数字,如 320,则输出应为“三二零”。以下是我尝试过的-

#include <stdio.h>
void main(){
long int num,rev=0 ;
printf("Enter any number to print in words: ");
scanf("%ld",&num);
while(num!=0){
    rev=(rev*10)+(num%10);
    num/=10 ;
}
while(rev!=0){
    long int x=rev%10;
    switch(x){
        case 0:
        printf("Zero ");
        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;
        case 9:
        printf("Nine ");
        break;
       }
   }
 }

现在的问题是,这段代码产生了一个无限循环,比如我输入一个数字,比如 21,然后它开始打印“二二二二......”直到无穷大。

请帮我解决这个问题。

您需要使“rev!=0”为真的东西,即在切换结束后为 rev = rev / 10。但是创建一个数组并分配零、一、二等并使用索引调用它们可能会更好,我想你可以考虑一下。

#include <stdio.h>
void main(){
long int num,rev=0 ;
printf("Enter any number to print in words: ");
scanf("%ld",&num);
while(num!=0){
    rev=(rev*10)+(num%10);
    num/=10 ;
}
while(rev!=0){
    long int x=rev%10;
    switch(x){
        case 0:
        printf("Zero ");
        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;
        case 9:
        printf("Nine ");
        break;
       }
       rev = rev / 10;
   }
 }

这是数组方法:

#include <stdio.h>
void main(){
long int num,rev=0 ;
printf("Enter any number to print in words: ");

num = 123456789;

const char arr[10][6]= {
    "Zero", "One", "two", "three", "four", "five", "six", "seven", "eight", "nine"
    };

while(num!=0){
    rev=(rev*10)+(num%10);
    num/=10 ;
}
while(rev!=0){
    long int x=rev%10;
    printf("%s ", arr[x]);
    rev = rev / 10;
   }
}