描述
求方程的根,用三个函数分别求当b^2-4ac大于0、等于0、和小于0时的根,并输出结果。
从主函数输入a、b、c的值。
注:结果需保留三位小数,且结果的排序为从大到小,即x1比x2大
输入
a b c
输出
x1=? x2=?
代码
#include<iostream>
using namespace std;
#include<iomanip>
#include<math.h>
int main()
{
double a, b, c;
cin >> a;
cin >> b;
cin >> c;
if (a == 0)//直接套公式分母含a会出现分母为0的错误,故需单独提出此情况应对
{
if (b == 0)
{
cout << "输入错误" << endl;
}
else
{
cout << setprecision(3) << std::fixed << "x1=" << -c / b << " " << "x2=" << -c / b << endl;
}
}
else //sqrt()为开根号,均为套公式
{
double T = b * b - 4 * a * c;
if (T == 0)
{
cout << setprecision(3) << std::fixed << "x1=" << -b / (2 * a) << " " << "x2=" << -b / (2 * a) << endl;
}
else if (T > 0) //判断一下谁大谁当x1
{
if ((-b + sqrt(T)) / (2 * a) > (-b - sqrt(T)) / (2 * a))
{
cout << setprecision(3) << std::fixed << "x1=" << (-b + sqrt(T)) / (2 * a) << " " << "x2=" << (-b - sqrt(T)) / (2 * a) << endl;
}
else
{
cout << setprecision(3) << std::fixed << "x1=" << (-b - sqrt(T)) / (2 * a) << " " << "x2=" << (-b + sqrt(T)) / (2 * a) << endl;
}
}
else //复数实部一样,虚部相反,易得谁大谁小不需作比较
{
cout << setprecision(3) << std::fixed << "x1=" << (-b) / (2.0 * a) << "+" << sqrt(-T) / (2.0 * a) << "i" << " " << "x2=" << (-b) / (2.0 * a) << "-" << sqrt(-T) / (2.0 * a) << "i" << endl;
}
}
}