[英]How do i find out which element in an array holds the highest value?
#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];
}
不要存储personPancake [E]的值。 将c的索引存储为大或小。
然后将您的比较更改为使用personPancake [大或小]。
尝试
#include <iostream>
using namespace std;
int main()
{
int personPancake[10];
int small, big;
int indexsmall=0,indexbig=0;
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];
indexbig=c;
}
if (personPancake[c] < small)
{
small = personPancake[c];
indexsmall=c;
}
}
cout << "Biggest: " << big << endl;
cout << "Index Biggest: " << indexbig << endl;
cout << "Smallest: " << small << endl << endl;
cout << "Index Smallest: " << indexsmall << endl << endl;
}
您需要存储c
当你发现的最大和最小的号码,你做的一样big
和small
int bigIdx, smallIdx;
for (int c = 0; c < 10; c++)
{
if (personPancake[c] > big)
{
big = personPancake[c];
bigIdx = c;
}
if (personPancake[c] < small)
{
small = personPancake[c];
smallIdx = c;
}
}
添加保存索引的变量
int main()
{
int personPancake[10];
int small, big, smallIndex, bigIndex;
for (int c = 0; c < 10; c++)
{
cout << "Enter how many pancakes person " << c + 1 << " ate: ";
cin >> personPancake[c];
}
big = small = personPancake[0];
bigIndex = smallIndex = 0;
for (int c = 0; c < 10; c++)
{
if (personPancake[c] > big)
{
big = personPancake[c];
bigIndex = c;
}
if (personPancake[c] < small)
{
small = personPancake[c];
smallIndex = c;
}
}
cout << "Biggest: " << big << endl;
cout << "Smallest: " << small << endl;
cout << "Biggest Index: " << bigIndex << endl;
cout << "Smallest Index: " << smallIndex << endl << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.