#include#include #include #include //使用向量 ,就包含向量的頭文件 #include #include using namespace std; int main() { cout << "please enter your first name :" << endl; string name; cin >> name; cout << "Hello " << name <<" !" << endl; cout << "please enter your midterm and final exam grades :" << endl; double midterm , final ; cin >> midterm >> final ; cout << "enter all your homework grades ." "followed by end-of-file :" << endl; vector homework; // 定義向量; double x; while(cin >> x) { homework.push_back(x); // 使用向量的好處是不用再像數組那樣事先定義數組大小,因為向量可以動態增長; } typedef vector ::size_type vec_sz; //由於覺得size_type類型名太長,所以用另一個名字作為代替 ; vec_sz size = homework.size() ; // 這個函數可以求得向量裡面元素的個數 if (size == 0){ cout << "endl" << "your must enter your greads ;" "please try again . " << endl; return 1; } sort(homework.begin() ,homework.end() ); // size函數的參數指定被排序的元素的范圍,所以用到了這兩個函數。begin指示第一個元素,end函指向緊跟在最後一個元素的之後的位置。 vec_sz mid = size/2; double median; median = size % 2 == 0 ? (homework[mid] + homework[mid - 1])/2 : homework[mid]; streamsize prec = cout.precision(); cout << "Your final grades is " << fixed << setprecision(3) << 0.2 * midterm + 0.4 * final +0.4 * median << setprecision(prec) << endl; return 0; }