简体   繁体   English

在几个整数之间找到最小值和最大值

[英]Finding min and max between several integers

Seeing the solution to this online on Stackoverflow https://stackoverflow.com/a/19200031/3185410 I tried to come up with another solution by setting max to -infinity and min to +infinity. 在Stackoverflow https://stackoverflow.com/a/19200031/3185410上在线查看此解决方案时,我试图通过将max设置为-infinity并将min设置为+ infinity来提出另一种解决方案。 The code here by @haccks works pretty fine. @haccks在这里的代码工作得很好。

#include <stdio.h>

int main()
{
int num, max, min;

printf ("Enter four numbers: ");
scanf ("%d", &num);
max = min = num;

for (int i = 0; i < 3; i++)
{ 
    scanf ("%d", &num);
    if (max < num)
        max = num;
    else if (min > num)
        min = num;
}

printf ("\n%d %d", max, min);
return 0;
}

Here's the one I came up with: 这是我想到的:

#include <stdio.h>
#include <limits.h>
void main()
{
int max,min,num,i;
min=INT_MAX;
max=INT_MIN;
for (i=0;i<=3;)
{
    i++;
    printf("Enter number %d : ",i);
    scanf("%d",&num);
    if (num>max) max=num;
    else if (num<min) min=num;
}
printf("max is %d and min is %d",max,min);
}

What am I doing wrong with that? 我在做什么错呢?

If the users input 5 then 6 you have : 如果用户输入5,则您有6:

for 5 : 5>-inf => max = 5 对于5:5> -inf => max = 5

for 6 : 6>5 => max = 6 but then min has become 5 and yet it is still INT_MAX. 对于6:6> 5 => max = 6,但是min变为5,但仍然为INT_MAX。

If you put if instead of else if , you loose in performance but have the right output I think (I cannot test right now). 如果使用if代替else if ,则性能会下降,但我认为输出正确(我现在无法测试)。

Set first input as min and max value. 将第一个输入设置为最小值和最大值。 And then add logic you wrote. 然后添加您编写的逻辑。 Here you had 2 lines of extra code but you don't have to sacrifice performance. 在这里,您有两行额外的代码,但是您不必牺牲性能。

#include <stdio.h>
#include <limits.h>
void main()
{
int max,min,num,i=0;
min=INT_MAX;
max=INT_MIN;
printf("Enter number %d : ",i+1);
scanf("%d",&num);
min=num;
max=num;
for (i=1;i<=3;)
{
    i++;
    printf("Enter number %d : ",i);
    scanf("%d",&num);
    if (num>max) max=num;
    else if (num<min) min=num;
}
printf("max is %d and min is %d",max,min);
}

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

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