简体   繁体   English

为什么C中的while循环不起作用?

[英]Why does this while-loop in C not work?

Ignoring the fact that negative numbers would not work here, why do positive integers create a infinite loop? 忽略负数在这里不起作用的事实,为什么正整数会创建无限循环? I tried many combinations, as simple as a = 20 and b = 4, but every single one creates a infinite loop. 我尝试了许多组合,如a = 20和b = 4一样简单,但每个组合都会创建一个无限循环。 What am I doing wrong or not seeing here? 我在做什么错或没有在这里看到?

#include <stdio.h>

int mdc(int a, int b) {
while (a != b) {
    if (a > b) 
        a = a - b;
    else b = b - a;
}
return a;
}

int main() {
    int a, b;
    printf("Valores mdc: \n");
    scanf("%d %d\n", &a, &b);
    printf("%d\n", mdc(a,b));
    return 0;
}

Not an infinite loop for the given input:- 给定输入不是无限循环:-

The thing is you have used \\n in the scanf as a result unless you enter some non-whitespace character - it waits for it. 问题是您在scanf使用了\\n ,除非您输入一些非空白字符-它会等待它。

What did the '\\n' do? '\\n'做什么的?

From standard explaining the why part - C11 N1570 § 7.21.6.25 从标准解释为什么部分- C11 N1570§ 7.21.6.2¶5

A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. 通过读取输入直到第一个非空白字符 (仍未读取)或直到无法读取更多字符为止, 执行由空白字符组成的指令。 The directive never fails. 该指令永远不会失败。

How to give input then? 那怎么给输入呢?

So it will work if you do this:- 因此,如果您这样做,它将起作用:-

>>> 20  4 Enter
<Somenonwhitespace> Enter

Better solution: 更好的解决方案:

Even better suggestion would be to use 更好的建议是使用

scanf("%d%d", &a, &b);

You don't need to specify the space as you did - %d directive skips over the white space characters. 您不需要像以前那样指定空格- %d指令跳过空白字符。

Code wise 明智的代码

if(scanf("%d%d", &a, &b)!=2){
    fprintf(stderr,"Error in input\n");
    exit(EXIT_FAILURE);
}

If you were to step the code in a debugger you would discover that the while loop is never even entered. 如果要在调试器中单步执行代码,则会发现while循环甚至都不会输入。 It is not a problem of an infinite while-loop. 这不是无限循环的问题。 Rather that scanf() never returns. 而是scanf()从不返回。

Change: 更改:

scanf("%d %d\n", &a, &b);

to

scanf("%d %d", &a, &b);

The line scanf("%d %d\\n", &a, &b); scanf("%d %d\\n", &a, &b); should be scanf("%d %d", &a, &b); 应该是scanf("%d %d", &a, &b); no \\n . \\n

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

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