C语言 在 C 程序中查找一系列数字的最大值和最小值(我的代码中出现错误)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27048576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:34:23  来源:igfitidea点击:

Finding max and min values in a series of numbers In C prgram (error in my code)

cfor-loopmaxmin

提问by Chrille

This may prove to be a really easy task but I can't seem to grasp what I've done wrong. I've looked for the answer that specifies exactly this execution but can't get it right. My program is supposed to only run 10 times only but it keeps looping until i close the application window. I am new to this so...

这可能被证明是一项非常简单的任务,但我似乎无法理解我做错了什么。我一直在寻找准确指定此执行但无法正确执行的答案。我的程序应该只运行 10 次,但它一直循环,直到我关闭应用程序窗口。我是新手,所以......

#include < stdio.h >

int main()

{


    int n, sum = 0, c, value;
    n = 10;
    int max = 0;
    int min = 0;



    printf("Write 10 numbers\n");

    for (c = 1; c <= n; c++)
    {
        scanf_s("%d", &value);


        if (c = 1)
        {
            max = value;
            min = value;


        }
        else if (value < max, c <= n)
        {
            max = value;
        }

        else if (value < min, c <= n)
        {
            min = value;
        }
    }

    printf("Biggest number is : %d\n", max);
    printf("Smallest number is : %d\n", min);



    return 0;
}

回答by Vlad from Moscow

Here you are using assignment operator =instead of comnparison operator ==

在这里您使用赋值运算符=而不是比较运算符==

if (c = 1)

The loop for finding minimum and maximum can be written simpler

查找最小值和最大值的循环可以写得更简单

for ( c = 1; c <= n; c++ )
{
    scanf_s( "%d", &value );

    if ( c == 1 )
    {
        max = value;
        min = value;
    }
    else if ( max < value )
    {
        max = value;
    }
    else if ( value < min )
    {
        min = value;
    }
}

回答by user1666959

Well, a version without the c == 1 comparison, seems to do it for me. Test cases included below. Please show a counter example, if you think it fails on reasonable input.

好吧,没有 c == 1 比较的版本似乎适合我。测试用例包括在下面。请展示一个反例,如果你认为它在合理的输入上失败了。

#include <stdio.h>
#include <limits.h>

int main(int argc, char **argv)
{
int value;
int min=INT_MAX, max=-INT_MAX, n=5;
for (int c = 1; c <= n; c++ )
  {
    scanf( "%d", &value );

    if ( max < value )
    {
      max = value;
    }
    if ( value < min )
    {
      min = value;
    }
  }
printf("min = %d\nmax = %d\n", min, max);
return 0;
}

stackoverflow$ ./minmax
2
-10
99
3
3
min = -10
max = 99
stackoverflow$ ./minmax
1
1 
1
1
1
min = 1
max = 1