习题 14.1 求一元二次方程式 的实根,如果方程没有实根,则输出有关警告信息。
代码:
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
void func(double , double , double);
double a, b, c;
double t;
cout << "输入a,b,c:" << endl;
cin >> a >> b >> c;
t = pow(b, 2) - 4 * a * c;
try
{
func(a, b, t);
}
catch(double)
{
cout << "此方程没有实根!" << endl;
}
return 0;
}
void func(double a,double b,double t)
{
if (t < 0)
{
throw a;
}
else if (t > 0)
{
cout << "两个实数根为:" << (-b + sqrt(t)) / 2 / a << " " << (-b - sqrt(t)) / 2 / a << endl;
}
else if (t == 0)
{
cout << "唯一实根为:" << (-b + sqrt(t)) / 2 / a << endl;
}
}