c语言如何求一元二次方程的根

avatar
作者
猴君
阅读量:0

可以使用以下代码来求解一元二次方程的根:

#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 %.2lfn", root1, root2);     } else if (discriminant == 0) {         root1 = -b / (2 * a);         root2 = root1;         printf("Roots are real and same: %.2lf and %.2lfn", root1, root2);     } else {         double realPart = -b / (2 * a);         double imaginaryPart = sqrt(-discriminant) / (2 * a);         printf("Roots are complex and different: %.2lf + %.2lfi and %.2lf - %.2lfin", realPart, imaginaryPart, realPart, imaginaryPart);     }      return 0; } 

用户输入三个系数 a、b、c,程序计算判别式的值,然后根据判别式的值判断方程的根的情况,并输出结果。

    广告一刻

    为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!