Home > Net >  Read the coefficients a,b,c of the quadratic equation ax^2 bx c and print it roots nicely for imagin
Read the coefficients a,b,c of the quadratic equation ax^2 bx c and print it roots nicely for imagin

Time:12-21

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

main() {
    int a, b, c, x, x1, x2;
    printf("enter the values of a,b,c:");
    scanf("%d%d%d", &a, &b, &c);
    printf("The quadratic equation is %d*pow(x,2) %d*x %d=0", a, b, c);

    if (pow(b, 2) - 4 * a * c >= 0) {
        x1 = (-b   sqrt(pow(b, 2) - 4 * a * c)) / 2 * a;
        x2 = (-b - sqrt(pow(b, 2) - 4 * a * c)) / 2 * a;
        printf("the roots of the equation are x1=%d,x2=%d", x1, x2);
    }
    else
        printf("roots of the equation in the form of x iy and x-iy");

    return 0;
}

Is this code alright for the given question, i had a bit confusion at that printing imaginary roots. could you please help

CodePudding user response:

  1. Use proper main prototype.
  2. Use floating point numbers instead of integers
  3. pow(b,2) == b*b
  4. / 2 * a -> / (2 * a)
int main(void) {
    double a, b, c, x, x1, x2;
    printf("enter the values of a,b,c:");
    if(scanf("%lf %lf %lf", &a, &b, &c) != 3) { /* handle error */}
    printf("\nThe quadratic equation is %f*x^2 %f*x %f=0\n", a, b, c);

    if (b*b - 4 * a * c >= 0) {
        x1 = (-b   sqrt(b*b - 4 * a * c)) / (2 * a);
        x2 = (-b - sqrt(b*b - 4 * a * c)) / (2 * a);
        printf("the roots of the equation are x1=%f,x2=%f\n", x1, x2);
    }
    else
    {
        double r = -b / (2*a);
        double z = sqrt(fabs(b*b - 4 * a * c));

        printf("the roots of the equation are x1 = %f   i%f, x2 = %f - i%f", r,z,r,z);
    }
}

https://gcc.godbolt.org/z/Ys1s8bWY7

  •  Tags:  
  • c
  • Related