C 将数字打印为文字

C 将数字打印为文字,c,C,如何将用户输入的数字打印为文字?例如,假设我输入了一个数字123,那么我希望打印第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++;

如何将用户输入的数字打印为文字?例如,假设我输入了一个数字123,那么我希望打印第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;
}

它正在打印一个额外的零。我如何解决这个问题?

额外的零是从这里来的:

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;
}

到目前为止你尝试了什么?你可能会发现你到底在哪里遇到了问题?你知道如何编写一个简单的C程序,比如Hello,world吗?如果是这样的话,您知道如何将用户输入读取为数字或字符串吗?你知道怎么打印字符串吗?你知道如何使用数组吗?你的问题给人的印象是,你确实需要先读一本教科书和/或一本教程,然后再问一些更具体的问题。这不是一个语言基础教程网站。一般的步骤可能是:1从用户那里读取数字,2创建一个循环来逐步遍历数字,3在循环内部将数字映射到表示数字的字符串,例如,1、2等并打印,4也在循环内部,打印a-如果需要,您还没有用完数字。这是一个简单的方法。完成这些步骤有多种方法。哦,对了。用sprintf或其他什么东西来获取chars。Subtrct“0”以获取垃圾箱。值,并使用该值将char*的常量数组索引为常量字符串;谢谢你。其他人有点像扼杀了我的好奇心。谢谢你的支持。
#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;
}