Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

How to print `1234567890` to `1 2 3 4 5 6 7 8 9 0` with `C`?

I am sorry, I do not want to work with string or char*.


Many days ago, I have created a small C code. Example, it allows me to input 1234567890; and, it will print 0 9 8 7 6 5 4 3 2 1 to screen:

int n;
printf("n = ");
scanf("%d", &n);
printf("
---

 m = ");
while (n)
{
    printf("%d ", n % 10);
    n = n / 10;
}
printf("

---

");

Now, I tried to create another script, which it allows me to input 1234567890; and, it will print 1 2 3 4 5 6 7 8 9 0 to screen.

#include <stdio.h>

void main()
{
    int n;
    printf("n = ");
    scanf("%d", &n);


    int i1 = 0, n1 = n;
    while (n1 != 0)
    {
        i1 = i1 + 1;
        n1 = n1 / 10;
    }

    printf("
---

m = ");

    int n2 = n;
    do
    {
        int k = 1, i2 = i1 - 1;
        while (i2 != 0)
        {
            k = k * 10;
            i2 = i2 - 1;
        }

        n2 = n2 / k;
        i1 = i1 - 1;

        printf("%d ", n2);

    }
    while (i1 != 0);

    printf("

---

");
}

My code does not print what I want to have: 1 2 3 4 5 6 7 8 9 0; it always print many zeros: 1 0 0 0 0 0 0 0 0 0.

Can you show me what mistakes in my code?


How to print 1234567890 to 1 2 3 4 5 6 7 8 9 0 with C?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By modifying your first small c code, you can obtain the expected display:

#include <stdio.h>

int main()
{
    int n;
    char sNumToText[80]; // to store n in ascii characters

    printf("n = ");
    scanf("%d", &n); // ask for 'n'

    sprintf(sNumToText,"%d",n); // convert integer to text
    printf("
---

 m = ");
    n=0;
    while (sNumToText[n]!='')
    {
        printf("%c ", sNumToText[n]); // print one digit and one space
        n ++;
    }
    printf("

---

");

    return (0);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...