Accelerated C++<3-6>

//如果学生没有参加任何考试,则平均成绩计算可能会出现除零的问题,除零在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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值