3

我有一个任务来计算 C 中的二次方程的根,应该很简单,我知道我需要用这个程序做什么,但我仍然遇到了问题。当根是虚数并且平方根内的项为零时,它可以正常工作。

但是当我输入会给出实根的系数 a、b 和 c 时,它给了我错误的答案,我无法弄清楚什么是错的。(我正在使用 a=2、b = -5 和 c=1 对其进行测试)

这是我的代码,它编译并运行,但给出了错误的答案。

#include<stdio.h>
#include<math.h>

int main()
{
    float a, b, c, D, x, x1, x2, y, xi;

    printf("Please enter a:\n");
    scanf("%f", &a);
    printf("Please enter b:\n");
    scanf("%f",&b);
    printf("Please enter c:\n");
    scanf("%f", &c);
    printf("The numbers you entered are: a = %f, b = %f, c = %f\n", a, b, c);


    D = b*b-4.0*a*c;
    printf("D = %f\n", D);
    if(D > 0){
        x1 =  (-b + sqrt(D))/2*a;
        x2 = ((-b) - sqrt(D))/2*a;
        printf("The two real roots are x1=%fl and x2 = %fl\n", x1, x2); 
    }
    if(D == 0){
        x = (-b)/(2*a);
        printf("There are two identical roots to this equation, the value of which is: %fl\n", x);
    }
    if (D<0){
        y = sqrt(fabs(D))/(2*a);
        xi = (-b)/(2*a);
        printf("This equation has imaginary roots which are %fl +/- %fli, where i is the square root of -1.\n", xi, y);
    }
    return 0;
}
4

1 回答 1

11

您没有正确计算结果:

x = y / 2*a

实际上被解析为

x = (y / 2) * a

所以你必须把括号括起来2*a

你要这个:

x = y / (2 * a)
于 2011-10-05T11:49:27.853 回答