标题本题要求实现一个函数,可以求出一次方程和二次方程的实数根,若怖满足求根的条件则抛出相应的异常并显示
//在这里给出函数被调用进行测试的例子:
#include
#include
using namespace std;
void root(double a,double b,double c,double& x1,double& x2);
int main()
{
double a,b,c;
cin>>a>>b>>c;
double x1,x2;
try
{
root(a,b,c,x1,x2);
cout<<“root:x1=”<<x1<<“,x2=”<<x2<<endl;
}
catch(int)
{
cout<<“Not a equation!”<<endl;
}
catch(const char* msg)
{
cout<<msg<<endl;
}
catch(…)
{
cout<<“Other Error!”;
}
return 0;
}
/* 请在这里填写答案 */
void root(double a, double b, double c, double& x1, double& x2)
{
if (a == 0) throw 1;
if (b * b - 4 * a * c < 0)
{
throw "No real root!";
}
double temp;
temp=b*b-4*a*c;
x1=(-b+sqrt(temp))/2*a;
x2=(-b-sqrt(temp))/2*a;
}