I have an assignment to compute the roots of quadratic equations in C, should be pretty simple and I know what I need to do with the program but I am having a problem nonetheless. It works fine when the roots are imaginary and when the term inside the square root is zero.
But when I enter coefficients a, b and c which would give real roots it gives me the wrong answer, and I cant figure out whats wrong. (I am testing it with a=2, b = -5 and c=1)
This is my code, it compiles and runs, but gives the wrong answer.
#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开发者_如何学C 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;
}
You don't calculate the result correctly:
x = y / 2*a
is actually parsed as
x = (y / 2) * a
so you have to put parentheses around 2*a.
you want this:
x = y / (2 * a)
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论