//如果学生没有参加任何考试,则平均成绩计算可能会出现除零的问题,除零在C++中并未定义,在这种情况下,我们要告知程序会出怎样的结果。
Hint
Look in the code and see which variable could be used as the denominator in division. Test that value against zero prior to the calculation and take appropriate action.
Solution
On my Windows 7 64-bit system, running the exercise as compiled by Visual Studio 2010 Professional, pressing end-of-file when the first grades are requested generates the following output:
#include <iomanip>
#include <ios>
#include <iostream>
#include <string>
using namespace std;
int main()
{
// ask for and read the student's name
cout << "Please enter your first name: ";
string name;
cin >> name;
cout << "Hello, " << name << "!" << endl;
// ask for and read the midterm and final grades
cout << "Please enter your midterm and final exam grades: ";
double midterm, final;
cin >> midterm >> final;
// ask for the homework grades
cout << "Enter all your homework grades, "
"followed by end-of-file: ";
// the number and sum of grades read so far
int count = 0;
double sum = 0;
// a variable into which to read
double x;
// invariant:
// we have read count grades so far, and
// sum is the sum of the first count grades
while (cin >> x) {
++count;
sum += x;
}
if (count == 0)
{
cout << endl << "No grades were entered. Your final grade cannot be calculated." << endl;
return 1;
}
// write the result
streamsize prec = cout.precision();
cout << "Your final grade is " << setprecision(3)
<< 0.2 * midterm + 0.4 * final + 0.4 * sum / count
<< setprecision(prec) << endl;
return 0;
}