我最近开始使用C++进行编码,并对以下代码有所怀疑。我在'throw'关键字遇到问题。在中位数或分数函数中它何时会给出错误? throw和domain_error的确切用法是什么?我会从等级或中位数函数得到错误信息吗?throw关键字的用法
#include<iostream>
#include<string>
#include<vector>
#include<iomanip>
#include<ios>
#include<algorithm>
#include<stdexcept>
using std::cout; using std::cin;
using std::vector; using std::endl;
using std::string; using std::streamsize;
using std::setprecision; using std::domain_error;
using std::istream;
double grade(double midterm, double final, double homework)
{
return 0.2*midterm+0.4*final+0.4*homework;
}
double median(vector<double> vec)
{
typedef vector<double>::size_type vec_sz;
vec_sz size= vec.size();
if(size==0)
{
throw domain_error("Median of an empty vector"); //when will i get this error msg??
}
sort(vec.begin(),vec.end());
vec_sz mid=size/2;
return size%2==0?(vec[mid]+vec[mid-1])/2:vec[mid];
}
double grade(double midterm, double final, const vector<double>& hw)
{
if(hw.size()==0)
{
throw domain_error("Student has done no homework");// when will i get this error?
}
return grade(midterm, final, median(hw));
}
istream& read_hw(istream& in, vector<double>& hw)
{
if(in)
{
hw.clear();
double x;
while(in>>x)
hw.push_back(x);
in.clear();
}
return in;
}
int main()
{
string name;
cout<<"Please enter your name:";
cin>>name;
cout<<"Hello "<<name<<"!"<<endl;
cout << "Please enter your midterm and final exam grades: ";
double midterm, final;
cin >> midterm >> final;
cout << "Enter all your homework grades, "
"followed by end-of-file: ";
vector<double> homework;
read_hw(cin, homework);
try {
double final_grade = grade(midterm, final, homework);
streamsize prec = cout.precision();
cout << "Your final grade is " << setprecision(3)
<< final_grade << setprecision(prec) << endl;
} catch (domain_error) {
cout << endl << "You must enter your grades. "
"Please try again." << endl;
return 1;
}
return 0;
}
你会得到它随时随地'大小收到以下错误消息== 0' 。 – Morwenn 2012-08-09 11:56:59
这段代码看起来很像* Accelerated C++ *,如果我可以这样说,这是一本很好的介绍性书籍。 – 2012-08-09 12:18:49
是它的一本书的代码。我现在就明白了。感谢大家的帮助。实际上,这本书不断地从各处跳来跳去,所以有时候会让像我这样的初学者感到困惑。 – pratZ 2012-08-09 16:37:50