throw domain_error有关问题
throw domain_error问题
题目是输入两次考试成绩和几次家庭作业成绩,按比例算出总成绩,如果家庭作业成绩没做的情况抛出异常
#include<iostream>
#include<string>
#include<stdexcept>
#include<ios>
#include<iomanip>
using std::cin;
using std::cout;
using std::endl;
int main()
{
cout<<"please enter your first name:";
std::string name;
cin>>name;
cout<<"Hello, "<<name<<"!"<<endl;
cout<<"Please enter your midterm and final exam grades:";
double midterm,final;
cin>>midterm>>final;
ut<<"Enter all your homework grades,"
"followed by end-of-file:";
int count=0;
double sum=0;
double x;
while(cin>>x)
{
++count;
sum+=x;
}
if(count==0)
throw std::domain_error ("The Student has done no homework;");
//上面这句有什么错,我这样写,运行的时候如果不输入作业成绩,直接ctrl+z会给我一个终止框,我要的是能抛出异常并且给语句提示,怎么改~
std::streamsize prec=cout.precision();
cout<<"Your final grade is"<<std::setprecision(3)
<<0.2*midterm+0.4*final+0.4*sum/count
<<std::setprecision(prec)<<endl;
return 0;
}
------解决方案--------------------
题目是输入两次考试成绩和几次家庭作业成绩,按比例算出总成绩,如果家庭作业成绩没做的情况抛出异常
#include<iostream>
#include<string>
#include<stdexcept>
#include<ios>
#include<iomanip>
using std::cin;
using std::cout;
using std::endl;
int main()
{
cout<<"please enter your first name:";
std::string name;
cin>>name;
cout<<"Hello, "<<name<<"!"<<endl;
cout<<"Please enter your midterm and final exam grades:";
double midterm,final;
cin>>midterm>>final;
ut<<"Enter all your homework grades,"
"followed by end-of-file:";
int count=0;
double sum=0;
double x;
while(cin>>x)
{
++count;
sum+=x;
}
if(count==0)
throw std::domain_error ("The Student has done no homework;");
//上面这句有什么错,我这样写,运行的时候如果不输入作业成绩,直接ctrl+z会给我一个终止框,我要的是能抛出异常并且给语句提示,怎么改~
std::streamsize prec=cout.precision();
cout<<"Your final grade is"<<std::setprecision(3)
<<0.2*midterm+0.4*final+0.4*sum/count
<<std::setprecision(prec)<<endl;
return 0;
}
------解决方案--------------------
try{...
if(***)
throw something;
....
}
catch(...)
{
}