分析:
因为a不为0,所以可能的情况少了很多。
问题在于:判断是否为0 上,由于double类型存在缺陷(计算机的原因吧),无法准确的表示0,因此只能表示无限趋于0,当一个double值的小数位数过多时,就会不够精准,只能将其和一个比较趋于0的小数进行比较,进而认为他“就是”0.
fabs():用来取double类型数据的绝对值
#include<iostream>
#include<cmath>
#include<iomanip>
using std::cin;
using std::cout;
using std::fabs;
using std::sqrt;
using std::fixed;
using std::setprecision;
#define eps1 1e-10
//1e-10是科学计数法
//表示: 1 * (-1) * 10^10
int main()
{
double a, b, c, x1, x2, d, e, f, g;
cin >> a >> b >> c;
d = b * b - 4.0 * a * c;
if (d<0 && fabs(d)>eps1)
{
cout << "No answer!";
}
else if (fabs(d) < eps1)
{
e = sqrt(d);
x1 = (-b + e) / (2.0 * a);
x2 = (-b - e) / (2.0 * a);
cout << fixed << setprecision(5) << "x1=x2="<< x1;
}
else
{
e = sqrt(d);
x1 = (-b + e) / (2.0 * a);
x2 = (-b - e) / (2.0 * a);
if (a<0 && fabs(a)>eps1)
{
cout << fixed << setprecision(5) << "x1=" << x1 << ";x2=" << x2;
}
else
{
f = x1;
g = x2;
x2 = f;
x1 = g;
cout << fixed << setprecision(5) << "x1="<< x1<< ";x2="<< x2;
}
}
}
由于本人水品有限,不能详细解释答案。。。欢迎一起讨论。