原创 使用vector计算学生成绩.cpp

2009-3-16 13:47 2305 5 5 分类: 软件与OS

https://static.assets-stash.eet-china.com/album/old-resources/2009/3/14/253b715d-4d1e-4e48-8854-68668bd2b760.rar《Accelerated C++中文版》


#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <string>
#include <vector>


using std::cin;     using std::cout;
using std::endl;    using std::string;
using std::setprecision;  using std::streamsize;
using std::vector;    using std::sort;


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: ";


 // a variable into which to read
 double x;
 vector<double> homework;


 // invariant:
 //   we have read count grades so far, and


 //   sum is the sum of the first count grades
 while (cin >> x) {
  homework.push_back(x);
 }


 typedef vector<double>::size_type vec_sz;
 vec_sz size = homework.size();


 if (size == 0) {
  cout << endl << "You must enter your grades. "
      "Please try again." << endl;
  return 1;
 }
 sort(homework.begin(), homework.end());


 vec_sz mid = size/2;
 double median;
 median = size % 2 == 0 ? (homework[mid] + homework[mid-1]) / 2
         : homework[mid];
 // write the result
 streamsize prec = cout.precision();
 cout << "Your final grade is " << setprecision(3)
   << 0.2 * midterm + 0.4 * final + 0.4 * median
   << setprecision(prec) << endl;
 system("PAUSE");
 return 0;
}

PARTNER CONTENT

文章评论0条评论)

登录后参与讨论
我要评论
0
5
关闭 站长推荐上一条 /3 下一条