vendredi 28 avril 2017

I'm writing a very simple letter grading system, are if statements the most efficient?

Code example:

question:
cout << "Enter the grade % you scored on the test: ";
cin >> userScore;

if (userScore == 100) {
    cout << "You got a perfect score!" << endl;
}   
else if (userScore >= 90 && userScore < 100) {
    cout << "You scored an A." << endl;
}
else if (userScore >= 80 && userScore < 89) {
    cout << "You scored a B." << endl;
}
//... and so on...
else if (userScore >= 0 && userScore < 59) {
    cout << "You scored an F." << endl;
}
goto question;

This code has a total of 6 if statements, and it looks very.. cookie-cutter-ish.. I guess? Is there a more efficient/optimal way to write this?

I looked up some example beginner projects for C++ and found this grading one, and it said knowledge of switch statements would be useful. I looked into that and my understanding is that, in this case, switch statements would effectively work the same way as if statements.

Aucun commentaire:

Enregistrer un commentaire