题解 | #计算一元二次方程#
计算一元二次方程
https://www.nowcoder.com/practice/7da524bb452441b2af7e64545c38dc26
#include <any>
#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
float a, b, c;
while (cin >> a >> b >> c) { // 注意 while 处理多个 case
if(a == 0)
{
cout<<"Not quadratic equation"<<endl;
}
else if (a != 0) {
float delt = b*b - 4*a*c;
if(delt == 0)
{
float x1,x2;
x1 = (((-1)*b)+sqrt(delt))/(2*a);
x2 = abs(x1);
if(x2 == 0)
{
x1 = 0;
}
cout<<fixed<<setprecision(2)<<"x1=x2="<<x1<<endl;
}
else if(delt > 0)
{
float x1,x2,d;
x1 = (((-1)*b)-sqrt(delt))/(2*a);
x2 = (((-1)*b)+sqrt(delt))/(2*a);
if (x1>x2) {
swap(x1, x2);
}
d = abs(x1);
if(d == 0)
{
x1 = 0;
x2 = 0;
}
cout<<fixed<<setprecision(2)<<"x1="<<x1<<";x2="<<x2<<endl;
}
else
{
float d = ((-1)*b)/(2*a),e;
float x1,x2;
x1 = (sqrt((-1)*delt))/(2*a);
x2 = abs(x1);
e = abs(d);
if(e == 0)
{
d = 0;
}
else {
d = d;
}
cout<<fixed<<setprecision(2)<<"x1="<<d<<"-"<<x2<<"i;x2="<<d<<"+"<<x2<<"i"<<endl;
}
}
}
}
// 64 位输出请用 printf("%lld")
测试中出现+0与-0,可以用绝对值进行处理。

