求一元二次方程的根

GitHub跳转原题关系图返回列表

按判别式正负分类输出两个实根、重根或共轭复根。

OJ: noi_openjudge

题目 ID: ch0104-20

难度:普及-

标签:数学分类讨论浮点数python

日期: 2026-07-30 23:01

题意

ax2+bx+c=0ax^2+bx+c=0 的根;按判别式输出两实根、重根或一对共轭复根,全部保留 5 位小数。

思路

D=b24acD=b^2-4acD>0D>0 时计算两个实根后排序,保证 x1>x2D=0D=0 时输出同一个根;D<0D<0 时实部是 b/(2a)-b/(2a),虚部绝对值是 D/2a\sqrt{-D}/|2a|。输出前把 -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;
}

复杂度

时间复杂度和额外空间复杂度均为 O(1)O(1)

总结

二次方程题的主体是判别式分类;格式要求同样重要,根的顺序、符号和负零都要控制。