简体   繁体   中英

Beginner problem with printf and scanf in C

I have a problem with scanf() and printf() function in a snippet of code like this:

#include <stdio.h>

int main() {
    int a;
    int b;
    int c;
    scanf("%d %d", &a, &b);
    while (c >= 2) {
        c = a % b;
        a = b;
        b = c;
        printf ("%d\n", c);
    }
    return 0;
}

What I expect to happen, and happens in my brother's Code::Block, is for the program to wait for input from stdin and then print to stdout the results, one per line, until it reaches the highest common divisor.

However, when I type it in vi and then compile it with gcc and run the program from my terminal, the program correctly takes the input but exit without returning anything to stdout .

If I comment out the scanf() line and hardcode any number to a and b variables, everything works as expected.

I'm trying to learn C and I've read basic documentation on the functions, but I can't help to understand this kind of behaviour. I've tried to put a setbuf(stdout, NULL) before declaring variables but nothing changed.

Can somebody give me a clue?

There's nothing wrong with your scanf and printf calls but, as others have mentioned, one obvious problem is that you are testing the value of an uninitialised variable ( c ).

Maybe, what you want is a do { ... } while (...); loop, rather than a simple while loop.

The following code will guarantee to execute the loop at least once and then, at the end of each loop, check whether or not to repeat it:

#include <stdio.h>
int main() {
    int a;
    int b;
    int c;
    scanf ("%d %d", &a, &b);
    do {
        c = a % b;
        a = b;
        b = c;
        printf ("%d\n", c);
    } while (c >= 2);
    return 0;
}

(Alternatively, initialise c with a value that is >= 2 , ie use the declaration: int c = 3; .)

For further discussion of the do .. while loop, see here: 'do...while' vs. 'while'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM