可以使用以下代码来求解一元二次方程的根:
#include#include int main() { double a, b, c; double discriminant, root1, root2; printf("Enter coefficients a, b and c: "); scanf("%lf %lf %lf", &a, &b, &c); discriminant = b * b - 4 * a * c; if (discriminant > 0) { root1 = (-b + sqrt(discriminant)) / (2 * a); root2 = (-b - sqrt(discriminant)) / (2 * a); printf("Roots are real and different: %.2lf and %.2lf\n", root1, root2); } else if (discriminant == 0) { root1 = -b / (2 * a); root2 = root1; printf("Roots are real and same: %.2lf and %.2lf\n", root1, root2); } else { double realPart = -b / (2 * a); double imaginaryPart = sqrt(-discriminant) / (2 * a); printf("Roots are complex and different: %.2lf + %.2lfi and %.2lf - %.2lfi\n", realPart, imaginaryPart, realPart, imaginaryPart); } return 0; }
用户输入三个系数 a、b、c,程序计算判别式的值,然后根据判别式的值判断方程的根的情况,并输出结果。