题解 | #计算一元二次方程#
计算一元二次方程
https://ac.nowcoder.com/acm/problem/21942
有这几点一定要注意:
1、当△=0时,有两个相等的根,需要注意分0和非0的情况
2、定义并初始化变量数据类型建议使用double,float存在精度问题
3、△<0时,建议虚部使用绝对值来表示,避免和原有的实部-虚部这里的-号冲突
4、△>0时,两个不等的跟,需要考虑b为负数的情况,这个时候x1=((-b)-sqrt(D))/(2*a)会大于x2=((-b)+sqrt(D))/(2*a),可以使用第三变量引入来交换x1和x2的值
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
double a=0.0;
double b=0.0;
double c=0.0;
while(cin>>a>>b>>c)
{
double x1=0.0;
double x2=0.0;
if(a==0.0)
cout<<"Not quadratic equation"<<endl;
if(a!=0.0)
{
double D=b*b-4*a*c;
if(D==0.0)
{
if(b==0.0)
{
x1=x2=0.0;
cout<<fixed<<setprecision(2)<<"x1=x2="<<x1;
}
else
{
x1=x2=(-b)/(2*a);
cout<<fixed<<setprecision(2)<<"x1=x2="<<x1<<endl;
}
}
else if(D>0.0)
{
double x1=((-b)-sqrt(D))/(2*a);
double x2=((-b)+sqrt(D))/(2*a);
if(x1>x2)
{
double temp=x1;
x1=x2;
x2=temp;
}
cout<<fixed<<setprecision(2)<<"x1="<<x1<<";"
<<"x2="<<x2<<endl;
}
else
{
double xb=fabs(sqrt(-D)/(2*a));
cout<<fixed<<setprecision(2)<<
"x1="<<(-b)/(2*a)<<"-"<<xb<<"i"<<";"<<
"x2="<<(-b)/(2*a)<<"+"<<xb<<"i"<<endl;
}
}
}
return 0;
}
查看10道真题和解析