[英]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.