1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
#include <iostream>
// <cstdlib> is not needed at all in this program so it was omitted
using namespace std;
// function prototypes
void getScores(double&, double&, double&);
double findAverage(double&, double&, double&, double&);
char toLetterGrade(double);
int main()
{
double midterm = 0.0; // initializing variables locally in main() to pass through to other functions
double final = 0.0; // it works fine in a small program like this and will help get you acquainted
double project = 0.0; // to the idea of modularization in your programs
double average = 0.0;
cout << "This program calculates your class average." << endl << endl;
// although you could get the scores and return the average, it's best to have one function carry out one operation
// in this case, one function gets the scores and the other finds the average. again, it's about modularization.
getScores(midterm, final, project);
// note how the functions are being called here.
// non-void are used like this in output streams to output whatever value is being returned.
// therefore, it works like a variable.
// you just do not explicity call on the name of the variable, although you could after calling it if you modified it again.
// doing so would just output 0.0, which is not what you're after
cout << "Calculated Average: " << findAverage(midterm, final, project, average) << endl <<
"Letter Grade: " << toLetterGrade(average) << endl;
system("pause"); // remember, this only goes inside of main() or else you'd pause the program elsewhere
return 0;
}
// prompts user for input
void getScores(double& midterm, double& final, double& project)
{
cout << "Enter midterm score: ";
cin >> midterm;
cout << "Enter final score: ";
cin >> final;
cout << "Enter project score: ";
cin >> project;
}
// finds the average and returns it when called upon in main()
double findAverage(double& midterm, double& final, double& project, double& average)
{
average = (midterm + final + project) / 3;
return average;
}
// depending on the average, it returns the letter grade.
// It works better than having it set up as a void function
// because it works on modularizing the program you have set up.
char toLetterGrade(double average)
{
char courseGrade = '\0';
if (average >= 90)
{
courseGrade = 'A';
}
else if (average >= 80 && average < 90)
{
courseGrade = 'B';
}
else if (average >= 70 && average < 80)
{
courseGrade = 'C';
}
else if (average >= 60 && average < 70)
{
courseGrade = 'D';
}
else if (average < 60)
{
courseGrade = 'F';
}
return courseGrade;
}
|