Use C language to find the root of a quadratic equation

If you want to write this example in C language, you need to know the mathematical formula.

The expression of the quadratic equation in one variable is: a * x * x + bx + c = 0 (where a ≠ 0)

The root discriminant is: Δ = b * b - 4 * a * c;

The formula for finding the root is:

 Code thought :

Manually input three coefficients, representing the quadratic coefficient, the first coefficient, and the constant;

Determine whether the input quadratic coefficient is 0, if it is 0, prompt "The first value entered is invalid, please re-enter!";

If the coefficient of the quadratic term is not 0, use the root discriminant to calculate whether the quadratic equation has roots;

If the discriminant Δ >= 0, it means that the equation has two roots, and output the roots;

If Δ < 0 , it prompts "the equation has no roots".

#include <stdio.h>
// 使用开根号 sqrt(d) 函数时,需要添加此头文件
#include <math.h>

int main()
{
    // 求一元二次方程的根
    // 代码思想:
    // 手动输入三个系数,分别代表二次项系数、一次项系数、常数项;
    // 判断输入的二次项系数是否为0,如果为0,提示“输入的第一个值不合法,请重新输入!”
    // 如果二次项系数不为0,利用根的判别式,计算一元二次方程是否有根;
    // 如果判别式 Δ >= 0 ,代表方程有两个根,输出根
    // 如果 Δ < 0 ,提示“方程无根”。

    float a , b , c, d, x1, x2;

    printf("请依次输入三个系数: ");
    scanf("%f %f %f", &a,&b,&c);

    if(a != 0)
    {
        d = b * b - 4 * a * c;                        // 根的判别式
        if(d >= 0)
        {
            x1 = ((-b + sqrt(d)) / (2 * a));            // 求根公式
            x2 = ((-b - sqrt(d)) / (2 * a));

            printf("x1 = %.2f;x2 = %.2f", x1, x2);
        }
        else
        {
            printf("方程无根");
        }
    }
    else
    {
        printf("输入的第一个值不合法,请重新输入!");
    }


    return 0;
}
For example 1: When the coefficient a = 0, b = 2, c = 1, the operation result is as follows

For example 2: When the coefficient a = 1, b = 2, c = 1, the operation result is as follows

For example 3: When the coefficient a = 1, b = 3, c = 2, the operation result is as follows

For example 4: When the coefficient a = 1, b = 0, c = 1, the operation result is as follows

Guess you like

Origin blog.csdn.net/m0_49456900/article/details/123850252