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 に答える