Colton Wiggs
Colton Wiggs

Reputation: 29

How to find max number from an input file of numbers

I need to find the maximum test score from an input file of test scores. The test scores are listed as percentages, one per line in the text file. I'm just not sure how to go about doing so. Right now my program just reads in the numbers and assigns them a letter grade.

I'm thinking I can assign the numbers to an array, but if there is a way to do this without using arrays I would prefer that.

string grade (double g) {
    string p;
    if (g >= 90) {
        p = "A";
    }
    if (g >= 80 && g < 90) {
        p = "B";
    }
    if (g >= 70 && g < 80) {
        p = "C";
    }
    if (g >= 60 && g < 70) {
        p = "D";
    }
    if (g < 60) {
        p = "F";
    }
    return p;
}
int main() {
    ifstream inData;
    try {
        inData.open("Scores.txt");
    }
    catch (int e) {
        return -1;
    }
    cout << "Percentage" << "   " << "Grade" << endl;
    cout << "-------------------" << endl;
    while (!inData.eof()) {
        double g;
        inData >> g;
        string p;
        p = grade (g);
        cout << "   " << g << "%" << "   --   " << p << endl;
    }
}

Upvotes: 0

Views: 213

Answers (2)

vijay
vijay

Reputation: 187

Try this;

int main() {
    ifstream inData;
    try {
        inData.open("Scores.txt");
    }
    catch (int e) {
        return -1;
    }
    cout << "Percentage" << "   " << "Grade" << endl;
    cout << "-------------------" << endl;
    double maxScore=-1;
    double g;
    while (inData >> g) {
        maxScore=fmax(maxScore,g);
        string p;
        p = grade (g);
        cout << "   " << g << "%" << "   --   " << p << endl;
    }
    cout <<"Maximum Score" is<<maxScore << endl;
}

Upvotes: 0

JonAmazon
JonAmazon

Reputation: 92

Since you are streaming the data in, you can use a 'compare and replace' type of algorithm to keep track of the maximum score.

First you would initialize a variable to be lower than all possible scores,

double max_score_so_far = 0.0;

Then every time you look at a new score you ask "is this bigger than the biggest I've seen so far?" If it is, then you replace your max so far with the current value.

if (g > max_score_so_far) { max_score_so_far = g; }

At the end of your file, max_score_so_far should contain the highest score.

Upvotes: 2

Related Questions