温馨提示×

c语言如何求一元二次方程的根

小亿
315
2024-06-07 10:51:23
栏目: 编程语言

可以使用以下代码来求解一元二次方程的根:

#include <stdio.h>
#include <math.h>

int main() {
    double a, b, c;
    double discriminant, root1, root2;

    printf("Enter coefficients a, b and c: ");
    scanf("%lf %lf %lf", &a, &b, &c);

    discriminant = b * b - 4 * a * c;

    if (discriminant > 0) {
        root1 = (-b + sqrt(discriminant)) / (2 * a);
        root2 = (-b - sqrt(discriminant)) / (2 * a);
        printf("Roots are real and different: %.2lf and %.2lf\n", root1, root2);
    } else if (discriminant == 0) {
        root1 = -b / (2 * a);
        root2 = root1;
        printf("Roots are real and same: %.2lf and %.2lf\n", root1, root2);
    } else {
        double realPart = -b / (2 * a);
        double imaginaryPart = sqrt(-discriminant) / (2 * a);
        printf("Roots are complex and different: %.2lf + %.2lfi and %.2lf - %.2lfi\n", realPart, imaginaryPart, realPart, imaginaryPart);
    }

    return 0;
}

用户输入三个系数 a、b、c,程序计算判别式的值,然后根据判别式的值判断方程的根的情况,并输出结果。

0