求三个数中的次大值,如何用C++来编写?

来源:百度知道 编辑:UC知道 时间:2024/07/04 08:15:30
如果是在10个数中求次大值,如何用C++编写?

实际上我将输入的三个数按从大到小排序了,输出中间的值就是你要求的

#include <iostream>
using namespace std;

int main()
{
int a, b, c;
cout << "Enter 3 Numbers:" << endl;
cin >> a >> b >> c;

int t;
if (a < b)
{
t = a;
a = b;
b = t;
}

if (a < c)
{
t = a;
a = c;
c = t;
}

if (b < c)
{
t = b;
b = c;
c = t;
}

cout << "输入的数据中次大值为:" << b << endl;

return 0;
}

你可以直接将他们排序,输出即可。

#include<iostream>
using namespace std;
int main()
{
int a[15],n,i,j,Max=0;
cin>>n;
for(i=1;i<=n;i++)cin>>a[i];
for(i=1;i<n;i++)
for(j=1;j<=n-i;j++)if(a[j]>a[j+1])swap(a[j],a[j+1]);
cout<<a[n-1];
return 0;
}