我已经用C++编写了一个代码,用于在数组中查找最大和第二大元素。代码工作正常,但问题是第二大数字的位置未更新。尽管第二大数字的值正确,但是其位置不正确。
#include<iostream>
using namespace std;
void main()
{
int DATA[10];
int largestNumber, secondLargestNumber, loc1, loc2;
cout << "Enter 10 numbers of array DATA" << endl;
for (int i = 0; i < 10; i++)
{
cin >> DATA[i];
}
largestNumber = DATA[1];
secondLargestNumber = DATA[2];
loc1 = 1;
loc2 = 2;
if (largestNumber < secondLargestNumber)
{
largestNumber = DATA[2];
secondLargestNumber = DATA[1];
}
for (int i = 2; i < 10; i++)
{
if (DATA[i]>largestNumber)
{
secondLargestNumber = largestNumber;
largestNumber = DATA[i];
loc1 = i;
}
else if (DATA[i]>secondLargestNumber)
{
secondLargestNumber = DATA[i];
loc2 = i;
}
}
cout << "Largest Number with location :"<<largestNumber<<" "<<loc1 << endl;
cout << "Second Largest Number location :" << secondLargestNumber<<" "<<loc2 << endl;
cin.get();
cin.get();
}
最佳答案
我可以建议一个更简单的解决方案吗?
#include <functional>
#include <set>
#include <iostream>
int main() {
std::set<int, std::greater<int>> s;
int input;
while(true) { // choose your stopping condition
cin >> input;
s.insert(input);
}
std::cout << (*s.begin()) << (*std::next(s.begin())) << std::endl;
}
关于c++ - 数组C++中最大和第二大的数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40388299/