Programming practice ~ one-dimensional quadratic equation solving problem

How to consider a quadratic equation solving problem in one variable:
Solution idea: first consider whether a is 0, if it is 0, then directly judge that the equation is not a quadratic equation of one variable. If it is not 0, judge the relationship between b^2-4ac and 0. If it is 0, judge that the equation has only one solution and directly output the solution as -b/2a. If it is greater than 0, judge that the equation has two solutions and output The solution is (-b+sqrt(b^2-4ac)/2a,(-b-sqrt(b^2-4ac))/2a, if it is less than 0, it is judged that the equation has no solution.

Note: Comparison between float and zero
Due to the way floating-point numbers are stored in memory, some floating-point numbers cannot be stored accurately in memory, which will result in a lack of precision, which may lead to inaccuracy in calculations. Therefore, == cannot be used to directly judge two floating point number. In this way, you must define a precision yourself, and comparing with the precision defined by yourself can reduce the error.
The procedure is as follows:

#define EXP 0.00000000001//Set an acceptable precision to ensure that the error is within the precision range
#include<math.h>
#include<stdio.h>
intmain()
{
        double a=0.0,b=0.0,c=0.0;
        scanf("%lf%lf%lf",&a,&b,&c);
        if(a>-EXP&&a<EXP)//means a is a number infinitely close to 0, approximately equal to 0
        {
              printf("\nThe equation is not a quadratic equation in one variable\n");
        }
        else
        {
        double disc=b*b-4*a*c;
        printf("\nThe equation is a quadratic equation");
        if(disc>-EXP&&disc<EXP)
        {
              printf("And there is only one unique solution: %lf\n",(-b)/2*a);
        }
        else if(disc>=EXP)
        {
              printf("And the two solutions are: %lf %lf\n",(-b+sqrt(disc)/2*a),(-b-sqrt(disc)/2*a));
        }
        else
        {
             printf("but no solution\n");
        }
 }
 return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325393247&siteId=291194637