gpt4 book ai didi

c++ - 我如何找出数组中的哪个元素具有最高值?

转载 作者:行者123 更新时间:2023-11-28 02:27:38 24 4
gpt4 key购买 nike

#include <iostream>

using namespace std;

int main()
{
int personPancake[10];
int small, big;

for (int c = 0; c < 10; c++)
{
cout << "Enter how many pancakes person " << c + 1 << " ate: ";
cin >> personPancake[c];
}

big = small = personPancake[0];

for (int c = 0; c < 10; c++)
{
if (personPancake[c] > big)
{
big = personPancake[c];
}

if (personPancake[c] < small)
{
small = personPancake[c];
}
}

cout << "Biggest: " << big << endl;
cout << "Smallest: " << small << endl << endl;
}

这是我在 atm 上的代码,我已经计算出最小和最大的数字,如您所见。我需要帮助找出拥有最大和最小值的元素的索引。

最佳答案

您可以设置另外两个变量来保存当前最小和最大索引。所以在你的 if 语句中......

int biggestIndex, smallestIndex;

if (personPancake[c] > big)
{
biggestIndex = c;
big = personPancake[c];
}

if (personPancake[c] < small)
{
smallestIndex = c;
small = personPancake[c];
}

关于c++ - 我如何找出数组中的哪个元素具有最高值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30003800/

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