简体   繁体   English

C 中 printf 和 scanf 的初学者问题

[英]Beginner problem with printf and scanf in C

I have a problem with scanf() and printf() function in a snippet of code like this:我在这样的代码片段中遇到了scanf()printf()函数的问题:

#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.我期望发生的事情,并且发生在我兄弟的 Code::Block 中,是让程序等待来自stdin ,然后将结果打印到stdout ,每行一个,直到达到最高公约数。

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 .但是,当我在vi输入它然后用gcc编译它并从我的终端运行程序时,程序正确地接受输入但退出而不返回任何东西stdout

If I comment out the scanf() line and hardcode any number to a and b variables, everything works as expected.如果我注释掉scanf()行并将任何数字硬编码到ab变量,一切都会按预期进行。

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.我正在尝试学习 C 并且我已经阅读了有关函数的基本文档,但我无法理解这种行为。 I've tried to put a setbuf(stdout, NULL) before declaring variables but nothing changed.我试图在声明变量之前放置一个setbuf(stdout, NULL)但没有任何改变。

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 ).您的scanfprintf调用没有任何问题,但正如其他人所提到的,一个明显的问题是您正在测试未初始化变量 ( c ) 的值。

Maybe, what you want is a do { ... } while (...);也许,你想要的是do { ... } while (...); loop, rather than a simple while loop.循环,而不是简单的while循环。

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; .) (或者,使用>= 2的值初始化c ,即使用声明: int c = 3; 。)

For further discussion of the do .. while loop, see here: 'do...while' vs. 'while'有关do .. while循环的进一步讨论,请参见此处: 'do...while' vs. 'while'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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