C语言中的简单乘法和算法

时间:2011-10-05 11:43:43

标签: c math quadratic

我有一个用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;
}

1 个答案:

答案 0 :(得分:11)

您无法正确计算结果:

x = y / 2*a

实际上被解析为

x = (y / 2) * a

所以你必须在2*a附近加上括号。

你想要这个:

x = y / (2 * a)