简体   繁体   中英

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. 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.

What did the '\\n' do?

From standard explaining the why part - C11 N1570 § 7.21.6.25

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.

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. It is not a problem of an infinite while-loop. Rather that scanf() never returns.

Change:

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

to

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

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

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