用C语言求一元二次方程组遇到如下问题。

2024-11-08 02:37:14
推荐回答(2个)
回答1:

#include 
int main(void)
{
    int repeat, ri;
    double a, b, c, d;

    scanf("%d", &repeat);
    for(ri = 1; ri <= repeat; ri++){
        scanf("%lf%lf%lf", &a, &b, &c);
        d=b*b-4*a*c;
        if(d<0){
            printf("x1 = %0.2f+%0.2fi\n", -b/(2*a), sqrt(-d)/(2*a));
            printf("x2 = %0.2f-%0.2fi\n", -b/(2*a), sqrt(-d)/(2*a));
        }
        else{
            if(a==0&&b==0&&c==0) //判断三个条件都成立,要用&&运算,  比较时用==,下同!
printf("参数都为零,方程无意义!\n");
            else{
                if(a==0&&b==0) //
printf("a和b为0,c不为0,方程不成立\n");
                else{
                    if(d==0) //
printf("x = %0.2f\n", -c/b);
                    else{
                        printf("x1 = %0.2f\n", (-b+sqrt(d))/(2*a));
                        printf("x2 = %0.2f\n", (-b-sqrt(d))/(2*a));
                    }
                }
            }
            
        }
    } 
    return 0;
}

严格来说,代码应该进行如下优化:
#include 
#include 
int main(void)
{
    int repeat, ri;
    double a, b, c, d;

    scanf("%d", &repeat);
    for(ri = 1; ri <= repeat; ri++){
        scanf("%lf%lf%lf", &a, &b, &c);
if(a==0&&b==0&&c==0) //先进行有效性检查
printf("参数都为零,方程无意义!\n");
else{
if(a==0&&b==0) //同上
printf("a和b为0,c不为0,方程不成立\n");
else{
d=b*b-4*a*c; //检查通过,再进行运算
if(d<0){
printf("x1 = %0.2f+%0.2fi\n", -b/(2*a), sqrt(-d)/(2*a));
printf("x2 = %0.2f-%0.2fi\n", -b/(2*a), sqrt(-d)/(2*a));
}
else{
                    if(d==0) //
printf("x = %0.2f\n", -c/b);
                    else{
                        printf("x1 = %0.2f\n", (-b+sqrt(d))/(2*a));
                        printf("x2 = %0.2f\n", (-b-sqrt(d))/(2*a));
                    }
                }
            }
            
        }
    } 
    return 0;
}

回答2:

判断条件写的不对
比如 if(a=0,b=0,c=0) 应该是 if(a==0&&b==0&&c==0)
其他类似
if(a=0,b=0) =》 if(a==0&&b==0)
if(d=0) =》 if(d==0)