How to find the roots of a quadratic equation in C

2 Answers

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

void quadratic_equation_roots(float a, float b, float c) {
    float discriminant = (b * b) - (4 * a * c);

    float root1, root2;
    if (discriminant > 0) {
        root1 = (-b + sqrt(discriminant)) / (2 * a);
        root2 = (-b - sqrt(discriminant)) / (2 * a);
        printf("root1 = %.2f\nroot2 = %.2f\n", root1, root2);
    }
    else if(discriminant == 0) {
        root1 = root2 = -b / (2 * a);
        printf("root1 = root2 = %.2f\n", root1);
    }
    else if(discriminant < 0) {
        float real = -b / (2 * a);
        float imaginary = sqrt(-discriminant) / (2 * a);
        printf("root1 = %.2f+%.2fi\nroot2 = %.2f-%.2fi\n", real, imaginary, real, imaginary);
    }
}

int main(void) {
    float a = 3, b = 5, c = -9;

    quadratic_equation_roots(a, b, c);
    printf("\n");

    a = 3; b = 5; c = 7;
    quadratic_equation_roots(a, b, c);
    printf("\n");

    a = 2; b = 4; c = 2;
    quadratic_equation_roots(a, b, c);

    return 0;
}




/*
run:

root1 = 1.09
root2 = -2.76

root1 = -0.83+1.28i
root2 = -0.83-1.28i

root1 = root2 = -1.00

*/

 



answered Jan 10, 2022 by avibootz
edited Jan 11, 2022 by avibootz
0 votes
#include <stdio.h>
#include <math.h>

enum { TWO = 2 };
enum { FOUR = 4 };
enum { SQUARE = 2 };

int main(void) {

    float a = 3, b = 5, c = -9;

    float root1 = (-b + sqrt(pow(b, SQUARE) - FOUR * a * c)) / (TWO * a);
    float root2 = (-b - sqrt(pow(b, SQUARE) - FOUR * a * c)) / (TWO * a);

    printf("%f\n", root1);
    printf("%f\n", root2);

    return 0;
}




/*
run:

1.088760
-2.755427

*/

 



answered Apr 23, 2022 by avibootz

Related questions

2 answers 219 views
1 answer 252 views
1 answer 247 views
1 answer 224 views
1 answer 231 views
1 answer 255 views
1 answer 166 views
...