x = (-b ± √(b^2 - 4ac)) / (2a)
Here, a
, b
, and c
are the coefficients of the quadratic equation ax^2 + bx + c = 0
, and x
represents the roots. The plus-minus symbol (±
) indicates that there are generally two solutions, one with a plus sign and one with a minus sign.
Below is a complete C program that calculates the roots of a quadratic equation and provides the results. The program prompts the user to enter the coefficients a
, b
, and c
, and then it calculates and displays the roots.
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c;
double discriminant, root1, root2;
printf("Enter the coefficients of the quadratic equation (a, b, c): ");
scanf("%lf %lf %lf", &a, &b, &c);
// Calculate the discriminant
discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
// Two real and distinct roots
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Root 1 = %.2lf\n", root1);
printf("Root 2 = %.2lf\n", root2);
} else if (discriminant == 0) {
// One real root (repeated)
root1 = -b / (2 * a);
printf("Root 1 = Root 2 = %.2lf\n", root1);
} else {
// Complex roots
double realPart = -b / (2 * a);
double imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Root 1 = %.2lf + %.2lfi\n", realPart, imaginaryPart);
printf("Root 2 = %.2lf - %.2lfi\n", realPart, imaginaryPart);
}
return 0;
}
Let's go through this code step by step:
We declare variables
a
,b
,c
,discriminant
,root1
, androot2
to store the coefficients and roots.We prompt the user to enter the coefficients
a
,b
, andc
.We calculate the discriminant (the value inside the square root) using the formula
discriminant = b * b - 4 * a * c
.We check the value of the discriminant to determine the nature of the roots:
- If the discriminant is greater than 0, there are two real and distinct roots.
- If the discriminant is equal to 0, there is one real root (repeated).
- If the discriminant is less than 0, there are complex roots.
Depending on the nature of the roots, we calculate and print the roots accordingly.
Here's an example of how the program works:
Enter the coefficients of the quadratic equation (a, b, c): 1 -3 2
Root 1 = 2.00
Root 2 = 1.00
In this example, the program finds the roots of the equation x^2 - 3x + 2 = 0
, which are x = 2
and x = 1
.