2.5多重else嵌套的二次方程求根

#include<stdio.h>
#include<math.h>
int main()
{
    double a, b, c, disc, x1, x2, realpart, imagpart;
    scanf("%lf,%lf,%lf", &a, &b, &c);
    
    printf("The equation");
    if(fabs(a) <= 1e-6){    //fabs是求绝对值,判断a是否小于0来判断是否是一个二次方程。 
        printf("is not a quadratic\n");
    }else{                  //否则(不小于0),则是二次方程,可以一般公式求解。 
        disc = b * b - 4 * a * c;   //disc 代表 b方-4ac,减少重复运算。 
        if(fabs(disc) <= 1e-6){     //内嵌的if,上一次逻辑下,判断delta是否为0 
            printf("has two equal roots:%8.4f\n", -b/(2*a));//判断成立,输出2根相等。 
        }else if(disc > 1e-6){      //delta大于0,有2个实根。 
            x1 = (-b + sqrt(disc)) /(2 * a);
            x2 = (-b - sqrt(disc)) /(2 * a);
            printf("has distinct real roots:%8.4f and %8.4f\n", x1, x2);
        }else{                      //否则,delta小于0,有2个复根 
            realpart = -b /(2 * a);
            imagpart = sqrt(-disc)/(2 * a);
            printf("has complex roots:\n");
            printf("%8.4f+%8.4fi\n", realpart, imagpart);
            printf("%8.4f-%8.4fi\n", realpart, imagpart);
        }
    }
    return 0;
 } 

注意:

由于disc是实数,而实数在计算和存储时会有一些微笑的误差,因此不能直接进行如下判断:“if(disc == 0)”因为这样可能会出现本来是0的量,由于上述误差而被判别为不等于0而导致结果错误。所以采取 的方法是判别disc的绝对值fabs(disc)是否小于一个很小的数(1e-6),如果小于此数,就认为disc == 0.

posted @ 2016-08-17 14:27  VRednow  阅读(226)  评论(0编辑  收藏  举报