【问题标题】:Can't stop while loop which has scanf inside无法停止内部有scanf的while循环
【发布时间】:2016-04-21 17:22:21
【问题描述】:
    #include <stdio.h>
    int main() {
        int test,i = 0,a = NULL;
        int max2 = 0;
        int n;

        int max = -1000000, min = 1000000;
        while (scanf("%d", &n) == 1 && max2 < 50)
        {
            if(n < min) { min = n; }     
            if(n > max) { max = n; }
            max2++;
         }
        printf("%d",min+max); 

        return 0;
    }

输入应该是这样的“1 5 8 9 10”,我不知道要输入多少个数字,所以我必须使用while循环。

【问题讨论】:

  • 不应该是scanf("%c", &amp;n),因为你有char n;
  • 我用 char 试图让 "\n" 停止但没用,我忘了把它转成 int 但没关系。
  • 你的意思是 max2 永远不会达到 50 并且 while 永远不会停止吗?因为,在我看来,你需要输入 50 个数字,然后它会停止,打印出 min+max 的总和
  • 最大输入数字为 50,但如果我输入低于 50 的数字,它应该可以工作。
  • 所以,如果您只是按 而不输入数字,您是否希望 scanf() 返回零?

标签: while-loop scanf


【解决方案1】:

尝试使用do whilescanf 放入循环中。

    #include <stdio.h>
    int main() {
        int test,i = 0,a = NULL;
        int max2 = 0;
        int n;

        int max = -1000000, min = 1000000;
        do{
            scanf("%d", &n);
            if(n < min) { min = n; }     
            if(n > max) { max = n; }
            max2++;
         }while ( n == 1 && max2 < 50)
        printf("%d",min+max); 

        return 0;
    }

【讨论】:

  • 它返回错误答案我的输入:1 5 8 9 它返回我 6 而不是 10
  • 这将终止循环,除非输入“1”。不完全是 OP 最初的意图。
  • 这是如何工作的?你在while ( n == 1 ...失去了我
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-17
相关资源
最近更新 更多