题解 | #计算一元二次方程#

计算一元二次方程

https://www.nowcoder.com/practice/7da524bb452441b2af7e64545c38dc26

#include <stdio.h>
#include <math.h>
int main()
{

    float a, b, c;
    float t = 0;//判别式
    //输入
    while(scanf("%f%f%f", &a, &b, &c) == 3)
    {
         //计算判别式的值
    t = b*b-4*a*c;
    //判断a
    if(0 == a)
    {
        printf("Not quadratic equation\n");
        return 0;
    }

    //根据判别式的情况分三种
    if(0 == t)//两实根相等
    {

        float x = -1*(b/ (2*a));
        if (x == 0.00)
        {
            printf("x1=x2=0.00\n");
        } 
        else {
        printf("x1=x2=%.2f\n", x);
        }
    }
    else if(t >0)//有两个不相等的实根
    {
        float x1 = ((-1*b)-sqrt(t))/(2*a);
        float x2 = ((-1*b)+sqrt(t))/(2*a);
        printf("x1=%.2f;x2=%.2f\n", x1, x2);
    }
    else//小于0,输出两个虚根? x1=实部-虚部i;x2=实部+虚部i   实部= -b / (2*a),虚部= sqrt(-△ ) / (2*a)
    {
        float s1 = (-1*b) / (2*a);//实部
        float s2 = sqrt(-1*t) / (2*a);//虚部
        printf("x1=%.2f-%.2fi;x2=%.2f+%.2fi\n", s1, s2, s1, s2);
    }

    }
   

    return 0;
}

全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务