设想有一个课程,学生的期末考试成绩占最终成绩的40%,期中考试成绩占20%,家庭作业的平均成绩占40%,下面这个程序便可以帮助学生计算他们的最终成绩:
#include<iostream>
#include<ios>
#include<iomanip>
#include<string>
using namespace std;
int main()
{
//ask for and read the student's nname
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 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;