gpt4 book ai didi

c++ - 数组C++中最大和第二大数

转载 作者:行者123 更新时间:2023-11-30 03:37:00 28 4
gpt4 key购买 nike

enter image description here

我用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com