"Algorithm Notes" Section 2.2-C/C++ Quick Start -> Sequential Structure Examples 3-5 Find the roots of a quadratic equation in one unknown

Example 3-5 Find the roots of a quadratic equation in one unknown

Description of the title
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, and b2-4ac>0.
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.
Sample input Copy
1 3 2
Sample output Copy
r1= -1.00
r2= -2.00
Because it is a question set of sequential structure, the solution method of sequential structure is adopted

#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 == 0)
        return 0;
    if (discriminant <= 0)
        return 0;
    else {
    
    
        r1 = (-b + sqrt(discriminant)) / (2 * a);
        r2 = (-b - sqrt(discriminant)) / (2 * a);
        printf("r1=%7.2f\nr2=%7.2f", r1, r2);
    }
    return 0;
}

In fact, this question can also be written with a selection structure, the number of lines of code will be reduced

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

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

Guess you like

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