This is a interesting problem I faced while solving an algorthmic problem. Using if and ">" operator gives erroneous output while std::max or initialzing with first element works.
Trying to find largest element and smallest element in array:
{
vector<int> plus{89, -83, 38, 58, 79, -80, 8, 19, 31, -95};
int plus_max = INT_MIN;
int plus_min = INT_MAX;
for(int i=1;i<N;i++){
if(plus[i]<plus_min)
plus_min = plus[i];
else if(plus[i]>plus_max)
plus_max = plus[i];
}
}
It gives output plus_max as 79(second largest) rather than 89 and plus_min as -95(CORRECT) but using max or initializing with first element and looping from second element works.
{
vector<int> plus{89, -83, 38, 58, 79, -80, 8, 19, 31, -95};
int plus_max = INT_MIN;
int plus_min = INT_MAX;
for(int i=1;i<N;i++){
plus_min = min(plus[i],plus_min);
plus_max = max(plus[i],plus_max);
}
}
I am unable to figure out why.
Aucun commentaire:
Enregistrer un commentaire