2017-04-16 180 views
-1

我想通过条件循环找出第二个最大值。我每次获得0作为第二最大值。我的错误在哪里,或者我该怎么做?如何查找第二个最大值在C++循环中

这里是我的代码:

#include<iostream> 
using namespace std; 
int main() 
{ 
    int sum=0,n, c=1; 
    int second_max=0; 
    float avg; 
    int max, min; 
    cin >> n; 
    sum = sum + n; 
    max = min = n; 
    while (n != 0) 
    { 
     cin >> n; 
     if (n==0) 
     break; 
     sum =sum+n; 
     c++; 
     if (max < n) 
      max = n; 
     if(second_max<n && max!=n) //code for finding second highest value 
      second_max = n; 
     if (min>n) 
      min = n; 
    } 
      cout << "sum: " << sum<<'\n'; 
      avg = float(sum)/c; 
      cout << "average: " << avg<<'\n'; 
      cout << "maximum no: " << max<<'\n'; 
      cout << "minimum no: " << min <<'\n'; 
      cout << "2nd maximum no: " << second_max << '\n'; 
} 

回答

1

试试这个:

if (max < n) 
    { 
     second_max = max; // the old max becomes second_max 
     max = n; // max gets the new 'n' value 
    } 
    if(second_max < n && n < max) 
    { 
     second_max = n; 
    } 

的问题是,你没有转变旧的“最大”价值“second_max”每当最大增加。所以second_max只是在数量不断增加的情况下才被更新(max会被改变,从来没有second_max)。

+0

谢谢你!你真好! –

+0

我需要稍微编辑第二个if语句,因为如果稍后键入* exactly * max的值(second_max将等于max),它会发生错误。 –

1

问题是当你找到一个新的最大值时,你应该把它设置为第二个最大值。如果max只改变一次而第二个max改变,那么还应该有其他声明。

while (n != 0) 
{ 
    cin >> n; 
    if (n == 0) 
     break; 
    sum = sum + n; 
    c++; 
    if (max < n) 
    { 
     second_max = max; 
     max = n; 
    } 
    if(second_max < n && n < max) 
    { 
     second_max = n; 
    } 


    if (min>n) 
     min = n; 
}