"Algorithm Notes" Section 2.3-C/C++ Quick Start -> Select the structure example 4-1 Find the root of a quadratic equation in one variable

Example 4-1 Find the roots of a quadratic equation in one variable

Title description
Find the root of the quadratic equation ax2+bx+c=0 in one variable. The three coefficients a, b, and c are input by the keyboard, and a cannot be 0, but b2-4ac>0 is not guaranteed.
The variables involved in the program are of type double.
Input
the three coefficients of the quadratic equation of one element separated by spaces, double-precision double type
output
. The two roots are output by branch as follows (note the newline at the end):
r1=first root
r2=second root When the
result is output, the width is 7 digits, including 2 decimal places.
If the equation has no real roots, output a line of information as follows (note the newline at the end):
No real roots!
Sample input Copy
1 2 3
Sample output Copy
No real roots!

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

int main() {
    
    
    double a, b, c, r1, r2;
    scanf("%lf%lf%lf", &a, &b, &c);
    double discriminant;
    discriminant = b * b - 4 * a * c;
    if (a) {
    
    
        if (discriminant >= 0) {
    
    
            r1 = (-b + sqrt(discriminant)) / (2 * a);
            r2 = (-b - sqrt(discriminant)) / (2 * a);
            printf("r1=%7.2f\nr2=%7.2f", r1, r2);
        } else {
    
    
            printf("No real roots!");
        }
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/DoMoreSpeakLess/article/details/109733127