I might ask this same question more than once as I go through this C++ book, hence 'Vol 1'. Anyhoo... here's the problem: "Write a program that gets three game scores from the user and displays the average."
And here's what I've done:
"//Write a program that gets three game scores from the user and calculates the average
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int TOTAL_GAMES = 3;
int game_1, game_2, game_3, total_score;
string player;
cout << "\nPlease enter your score for Game 1:\n";
cin >> game_1;
cout << "\nNow enter your score for Game 2:\n";
cin >> game_2;
cout << "\nGreat! Now do the same for the third game:\n";
cout << "Game 3: ";
cin >> game_3;
cout << "\nAwesome. Last thing, what's your first name?:\n";
cin >> player;
total_score = game_1 + game_2 + game_3;
cout << "\nWell " << player << " you did good! Your average score is " << (total_score / TOTAL_GAMES) << ". Well done!\n";
return 0;
}
"
Feels clunky to me though. How would it be improved and made to look prettier/be more efficient/concise?
Optimizing code Vol. 1
Well first off, you might want to consider storing the scores in a container if you want to store them at all. That way you can just use a loop for n games instead of having code duplication.
Quote:Original post by Falcon988
Feels clunky to me though. How would it be improved and made to look prettier/be more efficient/concise?
HINT:
Use an array of integers to store the scores, and use a looping mechanism to fill that array, and find the average.
You might want to do some input validation. cin can do some weird things if the user gives it a string when its expecting a number.
If you don't need to track the individual scores, you can just add this_score to total_score without having a list or array of scores.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement