按判别式正负分类输出两个实根、重根或共轭复根。
OJ: noi_openjudge
题目 ID: ch0104-20
难度:普及-
标签:数学分类讨论浮点数python
日期: 2026-07-30 23:01
题意
求
思路
令 x1>x2;-0.0 规范化为 0.0,避免违背题面格式。
代码
Python代码
python
import math
def normalize_zero(value):
return 0.0 if value == 0 else value
a, b, c = map(float, input().split())
discriminant = b * b - 4 * a * c
if discriminant > 0:
root1 = (-b + math.sqrt(discriminant)) / (2 * a)
root2 = (-b - math.sqrt(discriminant)) / (2 * a)
root1, root2 = max(root1, root2), min(root1, root2)
print(f"x1={root1:.5f};x2={root2:.5f}")
elif discriminant == 0:
root = normalize_zero(-b / (2 * a))
print(f"x1=x2={root:.5f}")
else:
real_part = normalize_zero(-b / (2 * a))
imaginary_part = abs(math.sqrt(-discriminant) / (2 * a))
print(f"x1={real_part:.5f}+{imaginary_part:.5f}i;x2={real_part:.5f}-{imaginary_part:.5f}i")C++代码
cpp
#include <bits/stdc++.h>
#include<iostream>
#include<cmath>
using namespace std;
int main(){
double a,b,c,x;
std::cin >> a >> b >> c;
if(b*b-4*a*c>0){
cout << "x1=";
cout << fixed << setprecision(5)
<< (-b+sqrt(b*b-4*a*c))/(2*a);
cout << ";x2=";
cout << fixed << setprecision(5) <<
(-b-sqrt(b*b-4*a*c))/(2*a);
}
else if(b*b-4*a*c==0){
std::cout << "x1=x2=" ;
cout << fixed << setprecision(5) <<
(-b+sqrt(b*b-4*a*c))/(2*a);
}
else{
x=-b/(2*a);
//if(x==0.0){
//x= -x;
//}
cout << "x1=";
cout <<fixed << setprecision(5) << x;
cout << "+";
cout <<fixed << setprecision(5) << sqrt(4*a*c-b*b)/(2*a);
cout <<"i;";
cout << "x2=";
cout <<fixed << setprecision(5) << x;
cout << "-";
cout <<fixed << setprecision(5) << sqrt(4*a*c-b*b)/(2*a);
cout <<"i";
}
return 0;
}复杂度
时间复杂度和额外空间复杂度均为
总结
二次方程题的主体是判别式分类;格式要求同样重要,根的顺序、符号和负零都要控制。