Reputation: 31
I have the following
int index = 0;
for (int i = start; i < end; ++i)
{
cout << spot.at(i) << ' '; // prints 190 2 94
if (spot.at(i) > spot.at(index)) // finds the greatest value which is 190 so gives back 0 bc spot.at(0) has the highest value
{
index = i;
cout << index;
}
}
return index;
so when I compile I get 190 instead of the index which is 0. If I do not put the return max I get 0 but I need to return the index with the greatest value so I have to include "return". It was working fine but then it keep fluctuating, so sometimes it works other times it doesnt. Now I tried it again with these values129 55 161 67 107 187 164 102 72 135 197 197 start = 0 and end = 11 but it keeps giving me 197 instead of the index which is 10. If I print index it does give me 10 but when I return index it gives me nothing. Still not quite sure whats going wrong, thanks your help is appreciated.
Upvotes: 2
Views: 2299
Reputation: 8576
int max_index = 0;
for (int i = start; i < end; ++i)
{
cout << spot.at(i) << ' '; // prints 190 2 94
if (spot.at(i) > spot.at(max_index)) // find the greatest value
{
max_index = i;
}
}
return max_index;
Upvotes: 3
Reputation: 4471
You want to track both the max
value, and the index that the max
value is located at. Then, when you find a new max
, you update both the max
and the maxIndex
.
int max = spot.at(0);
int maxIndex = 0;
for (int i = start; i < end; ++i)
{
cout << spot.at(i) << ' '; // prints 190 2 94
if (spot.at(i) > max) // find the greatest value
{
max = spot.at(i);
maxIndex = i;
}
}
return maxIndex;
Upvotes: 2