3-0. Compile, execute, and test the programs in this chapter.
#include <iostream>
#include <vector>
#include <ios>
#include <iomanip>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
cout<<"input name:";
string name;
cin>>name;
cout<<endl;
cout<<"input your midterm & final score:";
double midterm,fin;
cin>>midterm>>fin;
cout<<endl;
cout<<"input your homework scores:"<<endl;
vector<double> homework;
double hw;
while(cin>>hw)
{
homework.push_back(hw);
}
cout<<endl;
sort(homework.begin(),homework.end());//sort the homework score
typedef vector<double>::size_type size_tp;
size_tp size=homework.size();//homework size
int mid=size/2;
double mid_hw=size%2==0?(homework[mid-1]+homework[mid])/2:homework[mid];
streamsize proc=cout.precision();
cout<<setprecision(4)<<"the score is:"<<0.4*fin+0.4*mid_hw+0.2*midterm<<
setprecision(proc)<<endl;
return 0;
}
lyj@qt:~/Desktop$ g++ 3-0.cpp -o 3-0
lyj@qt:~/Desktop$ ./3-0
input name:tianya
input your midterm & final score:98 99
input your homework scores:
99
100
98
97
99
100
the score is:98.8
lyj@qt:~/Desktop$
3-1. Suppose we wish to find the median of a collection of values. Assume that we have read some of the values so far, and that we have no idea how many values remain to be read. Prove that we cannot afford to discard any of the values that we have read. Hint: One proof strategy is to assume that we can discard a value, and then find values for the unread—and therefore unknown—part of our collection that would cause the median to be the value that we discarded.
Ans:根据题中假设证明,假设输入8,10,11,15时丢弃一数值15,然后继续读入剩余数值16,17,此时数据集合为8,10,11,16,17,中值为11,而不等于丢掉的值15。故假设不成立,原命题成立。</