Class scores Write a program that calculates the total grade for N classroom exercises as a percentage. The user should input the value for N followed by each of the N scores and totals. Calculate the overall percentage (sum of the total points earned divided by the total points possible) and output it as a percentage.
#include <iostream>
using namespace std;
int main()
{
float s; //score
float t; //total possible points
float p; //percentage
int n; // # of exercises
cout << "Enter the number of exercises to input: "<<endl;
cin >> n;
for (int i=1; i <=n; i++)
{
cout << "Enter the score received for Exercise " <<endl;
cin >> s;
cout << "Enter the total points possible for Exercise " << endl;
cin >> t;
p = (s/t)*100;
}
cout << "your total is " << s << " out of "<< t << " or " << p << "%" << endl;
return 0;
}
For some reason when I run it, it only calculates the percentage of the last exercise inputted and not the total score and points. I have no idea what I am doing wrong.
>Solution :
You need to store the cumulative score and potential points as you go. Then at the completion of the loop you can calculate an average.
Use double rather than float unless you have a very specific reason not to, and you may wish to use iomanip to meaninfully format your floating point values on output.
Note that the variables to hold each score and available points number can be locally scoped to the loop as they are never used afterwards.
double s = 0;
double p = 0;
for (int i = 1; i <= n; i++)
{
double s_temp, p_temp;
cout << "Enter the score received for Exercise " <<endl;
cin >> s_temp;
cout << "Enter the total points possible for Exercise " << endl;
cin >> p_temp;
s += s_temp;
p += p_temp;
}
double avg = s / p * 100;
Now, you may wish to actually store all of the input grade info points. For that you might define a struct to hold both points of information, and then create a std::vector of those structs.
struct Grade {
double score;
double points;
};
int main() {
int n;
std::cout << "Number of grades? ";
std::cin >> n;
std::vector<Grade> grades(n);
for (auto &g : grades) {
std::cout << "Enter score: ";
std::cin >> g.score;
std::cout << "Out of points: ";
std::cin >> g.points;
}
double total_score, total_points;
for (const auto &g : grades) {
total_score += g.score;
total_points += g.points;
}
double avg = total_score / total_points * 100;
}