1. Quadratic Equation
Aim:
To write a C program to find the roots of a Quadratic equation.
Program:
#include <math.h>
#include <stdio.h>
int main()
{
double a, b, c, discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
discriminant = b * b - 4 * a * c;
// condition for real and different roots
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Real and Different roots \n");
printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
}
// condition for real and equal roots
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("Real and Equal roots \n");
printf("root1 = root2 = %.2lf;", root1);
}
// if roots are not real
else {
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("Real and Imaginary roots \n");
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart, realPart, imagPart);
}
return 0;
}
Sample Input 1:
E Enter coefficients a, b and c: 1 3 1
Sample Output 1:
R Real and Different roots
r root1 = -0.38 and root2 = -2.62
--------------------------------Sample Input 2:
Enter coefficients a, b and c: 1 2 1
Sample Output 2:
Real and Equal roots
root1 = root2 = -1.00;
--------------------------------
Sample Input 3:
Enter coefficients a, b and c: 1 1 1
Sample Output 3:
Real and Imaginary roots
root1 = -0.50+0.87i and root2 = -0.50-0.87i
--------------------------------
No comments:
Post a Comment