简体   繁体   English

如何停止 output 的无限循环?

[英]How to stop infinite looping the output?

I have code with a function that returns the biggest digit from a number.我有一个 function 的代码,它从一个数字中返回最大的数字。 The requirement is to enter numbers until something that is not a number is entered.要求是输入数字,直到输入不是数字的内容。 When something that isn't a number is entered, the program is supposed to stop, but in my case it just starts an infinite loop that prints the last result that the function returned.当输入不是数字的东西时,程序应该停止,但在我的情况下,它只是启动一个无限循环,打印 function 返回的最后一个结果。 Here is the code:这是代码:

#include <stdio.h>
int maxDigit(int n){
    int temp = n, maxDig = 0;
    while(temp){
        int digit = temp % 10;
        if(digit > maxDig){
            maxDig = digit;
        }
        temp /= 10;
    }
    return maxDig;
}
int main()
{
    int n = 1, broj;
    while(n){
    if(scanf("%d", &broj)); 
    printf("%d\n", maxDigit(broj)); 
    }
    return 0;
}

What might be the problem?可能是什么问题?

You can look at the return value of scanf to see if you read a valid integer, and you can use break to terminate your loop.您可以查看scanf的返回值,看看您是否读取了有效的 integer,您可以使用break来终止循环。 The n variable in your main function just had a constant value so I got rid of it, and cleaned up the function in a few other ways. main function 中的n变量只有一个常数值,所以我去掉了它,并以其他几种方式清理了 function。 Here is my resulting code:这是我的结果代码:

...
int main() {
  while (1) {
    int input;
    if (scanf("%d", &input) != 1) { break; }
    printf("%d\n", maxDigit(input)); 
  }
}

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

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