当前位置:网站首页>Functions: Finding Roots of equations

Functions: Finding Roots of equations

2022-07-06 14:35:00 |Light|

requirement

Programming , Find the equation ax2+bx+c=0 The root of the , Solve with three functions respectively b2-4ac Greater than 0, be equal to 0 And less than 0 Root of time .

Code

#include<stdio.h>
#include<math.h>
#define EPSILON 1E-6

// Calculate and output two unequal real roots 
void fun1(double a,double b,double c)
{
    
    double x1,x2;
    //  Please add code below 
    // ********** Begin ********** 
    int s = b*b-4*a*c;
    if(s>0)
    {
    
        x1 = ((0-b)+sqrt(s))/(2*a);
        x2 = ((0-b)-sqrt(s))/(2*a);
    }

    // ********** End **********
    printf(" The equation has two unequal real roots :%.2f,%.2f\n",x1,x2);

}

// Calculate and output two equal real roots 
void fun2(double a,double b,double c)
{
    
    double x1,x2;
    //  Please add code below 
    // ********** Begin ********** 
     int s = b*b-4*a*c;
    if(s==0)
    {
    
        x1 = (0-b)/(2*a);
        x2 = (0-b)/(2*a);
    }
    // ********** End **********
    printf(" The equation has two equal real roots :%.2lf,%.2lf\n",x1,x2);

}

// Calculate and output two conjugate complex roots 
void fun3(double a,double b,double c)
{
    
    double p,q;
    //  Please add code below 
    // ********** Begin ********** 
     int s = b*b-4*a*c;
    if(s<0)
    {
    
        p = (0-b)/(2*a);
        q = sqrt(0-s)/(2*a);
    }

    // ********** End **********
    printf(" The equation has two conjugate complex roots :%.2lf+%.2lfi,%.2lf-%.2lfi\n",p,q,p,q);
    
}

// Calculate the root of the equation 
void fun(double a,double b,double c)
{
    
    double delta=b*b-4*a*c;
    if(fabs(delta)>EPSILON)
    {
    
        if(delta>0)
            fun1(a,b,c);
        else
            fun3(a,b,c);
    }
    else
        fun2(a,b,c);
}

test

Test input
3 6 8

Output
The equation has two conjugate complex roots :-1.00+1.29i,-1.00-1.29i

原网站

版权声明
本文为[|Light|]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060918542849.html