jeudi 11 octobre 2018

My If Else statement is not working to provide maximum value in a vector (C++)

I am trying to return the max. value in a vector in C++, but I am constantly getting only the last value as the response (I am guessing it is because the if-else loop is somehow not doing the comparison and is just assigning the next value to "maxVal"). For example, the below code is returning 30 as the answer. What am I doing wrong? Can you please help?

Below is the code ->

#include <iostream>
#include <cstdlib>
#include <cmath>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

double max (const vector<double>& myVector)   {
int n = myVector.size();
double maxVal;
for (int i=0; i<=n-1; i++) {
    if (maxVal <= myVector[i+1])  {
        maxVal = myVector[i+1];

}
    else {
        maxVal = myVector[i];
    }

}
return maxVal; 
}

int main() {
vector<double> testVector;
testVector.push_back(10.0);
testVector.push_back(200.0);
testVector.push_back(30.0);
cout << max(testVector);
return 0;

}

Aucun commentaire:

Enregistrer un commentaire