C语言 在不使用数组的情况下从标准输入中查找第二大元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25493707/
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:18:07  来源:igfitidea点击:

Find 2nd largest element from stdin without using an array

c

提问by Nidhi Murthy

#include<stdio.h>

int main() {
    int i, m1, m2, n, num;
    puts("\n");
    scanf("%d",&n);
    for(i = 0; i < n; i++) {
         scanf("%d", &num);
         if(i == 0) {
              num = m1 = m2;
         }
         if(num > m1) {
              m2 = m1; 
              m1 = num; 
         } else if(num > m2) {
              m2 = num;
         }
     }
    return 0;
}

my stdin: -950 -588 -169 -187 -445 400 -1

我的标准输入: -950 -588 -169 -187 -445 400 -1

I have to get stdout: -169but its showing stdout: \n

我必须得到标准输出:-169但它显示标准输出:\n

Note: I want to solve this problem without arrays.

注意:我想在没有数组的情况下解决这个问题。

回答by macfij

the statement:

该声明:

num = m1 = m2;

is wrong and it does not cause the three variables to have the same value. You need to assign m1 and m2 to num. You are overwriting the variable that you previously had read. Change it to:

是错误的,它不会导致三个变量具有相同的值。您需要将 m1 和 m2 分配给 num。您正在覆盖之前读取的变量。将其更改为:

m1 = num;
m2 = num;

Then, print out the m2.

EDIT:

As others found out, the -1 states for end of your input. Adding simple if statement solves the problem and for your input -169 is the second largest element.
Full code:

然后,打印出 m2。

编辑:

正如其他人发现的那样,-1 表示输入结束。添加简单的 if 语句可以解决问题,对于您的输入,-169 是第二大元素。
完整代码:

#include<stdio.h>
int main(){
int i, m1, m2, n, num;
puts("\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
     scanf("%d",&num);
     if(i==0)
     {
          m1 = num;
          m2 = num;
     }
     else if(num == -1)  /* if -1 was read, then terminate the loop. */
     {
         break;
     }
     else if(num>m1)
     {
          m2 = m1; 
          m1 = num; 
     }
     else if(num>m2)
     {
          m2=num;
     }
 }
printf("%d\n",m2);
return 0;
}

For input:

对于输入:

7
-950 -588 -169 -187 -445 400 -1

and current code output is -169.

当前代码输出为-169。


Another EDIT:
Ok, your code is wrong because of the scanf for number of elements. In future It would be helpful if you were more clear about your problems. I hope that following code will work for you.


另一个编辑:
好的,由于元素数量的 scanf,您的代码是错误的。将来如果您更清楚自己的问题,将会很有帮助。我希望下面的代码对你有用。

#include <stdio.h>

int main(void)
{
    int curr, second, first;
    scanf("%d", &curr);
    second = curr;
    first = curr;
    while (1) {
        scanf("%d", &curr);
        if (curr == -1) {
            break;
        }
        if (curr > first) {
            second = first;
            first = curr;
        }
        else if (curr > second) {
            second = curr;
        }
    }
    printf("%d\n",second);
    return 0;
}

回答by ROHAN

/* Program to find the second largest number without using array */
        main()
        {
         int num,large=0,slarge=0,i=0;
         clrscr();
         printf("Enter the number:");
         while(i<10)
         {
          scanf("%d",&num);
          if(i==0)
          {
          large=num;
          }
          else if(num>large)
          {
           slarge=large;
           large=num;
          }
          else if(num>slarge)
          {
           slarge=num;
          }
          i++;
         }
         printf("Large number:%d",large);
         printf("\nSecond large=%d",slarge);
         getch();
         return 0;
        }

回答by David C. Rankin

The problem with your code is you are using m2uninitialized. To correct the problem, set m2to some reasonable negative number (like the smallest integer allowed). Here we are just using a negative number for example:

您的代码的问题是您使用的是m2未初始化的。要纠正问题,请设置m2为某个合理的负数(例如允许的最小整数)。例如,这里我们仅使用负数:

m2 = -1000000;

outout

出局

argument [0]:  -950
argument [1]:  -588
argument [2]:  -169
argument [3]:  -445
argument [4]:  400
argument [5]:  -1

m1: 400
m2: -1

Your code does what you intend. -1is the second largest number (400is the largest). If you want -169, then you want the 3rd largest. Remember:

您的代码按照您的意图执行。-1是第二大数字(400是最大的)。如果你想要-169,那么你想要第三大。记住:

ALWAYS INITIALIZE YOUR VARIABLES

始终初始化您的变量

回答by Farouq Jouti

here's a working and simpler version :

这是一个工作且更简单的版本:

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

  int main(int argc , char** argv)
  {
    int m1 , m2 , rc = 1;
    m1 = m2 = INT_MIN ;

    while(rc)
    {
            scanf("%d" , &rc);
            if(rc > m1)
                    m1 = rc;
            else if(rc < m1 && rc > m2)
                    m2 = rc;

    }
    printf("%d\n" , m2);

  }

回答by Kulamani

/*Second largest elements in a given array*/
#include <stdio.h>
int SecondMax(int a[], int n) // n= array size 
{
    int max1, max2;     //assume max1 as largest and max2 is second largest 
    max1= max2= a[0];   //Initialize first element of array
    for(int i=0; i<n; i++)
    {
        if(a[i] > max1) //check each elements of array with max1 
        {
            max2= max1; 
            max1= a[i];
        }
        else if(a[i] > max2)
            max2= a[i];
    }
    return max2;
}

int main()  
{
    int a[10]={2, 54, 8, 9 ,12, 6, 3, 7, 32, -5};

    printf("\nmax2= %d", SecondMax(a, 10)); //print return value 
    return 0;
}