Write a program in C language to solve quadratic equations with one variable.
Here is an example of finding the roots of a quadratic equation in C language.
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c;
double discriminant, root1, root2;
printf("请输入一元二次方程的系数:\n");
printf("a = ");
scanf("%lf", &a);
printf("b = ");
scanf("%lf", &b);
printf("c = ");
scanf("%lf", &c);
discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("方程有两个实根:\n");
printf("根1 = %lf\n", root1);
printf("根2 = %lf\n", root2);
} else if (discriminant == 0) {
root1 = -b / (2 * a);
printf("方程有一个实根:\n");
printf("根 = %lf\n", root1);
} else {
double realPart = -b / (2 * a);
double imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("方程有两个虚根:\n");
printf("根1 = %lf + %lfi\n", realPart, imaginaryPart);
printf("根2 = %lf - %lfi\n", realPart, imaginaryPart);
}
return 0;
}
This program starts by asking the user to input the coefficients a, b, and c of a quadratic equation, then calculates the discriminant. Based on the value of the discriminant, the program determines the roots of the equation and outputs the result. If the discriminant is greater than 0, the equation has two real roots; if the discriminant is equal to 0, the equation has one real root; if the discriminant is less than 0, the equation has two complex roots.