C语言:求ax^2+bx+c=0方程的解

求大神瞧瞧哪里有问题QAQ谢谢!!

C语言:求ax^2+bx+c=0方程的解过程如下:

#include <stdio.h>
#include <math.h>
int main()
{

   // 定义变量
   double a, b, c, determinant, root1,root2, realPart, imaginaryPart;
   printf("Enter coefficients a, b and c: ");//提示输入三个参数
   scanf("%lf %lf %lf",&a, &b, &c); //输入三个系数
   determinant = b*b-4*a*c; //求出δ的值

  

 // 判断如果determinant 大于0,方程就有两个实数根

   if (determinant > 0)
   {
     // sqrt() 函数求出平方根
       root1 = (-b+sqrt(determinant))/(2*a);
       root2 = (-b-sqrt(determinant))/(2*a);
       printf("root1 = %.2lf and root2 = %.2lf",root1 , root2);
   }

   //有两个相等的实数根
   else if (determinant == 0)
   {
       root1 = root2 = -b/(2*a);
       printf("root1 = root2 = %.2lf;", root1);
   }
   //没有实数根,只有虚数
   else
   {
       realPart = -b/(2*a); //获取根的实部
       imaginaryPart = sqrt(-determinant)/(2*a);//获取根的虚部

       printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imaginaryPart, realPart, imaginaryPart); //打印虚数根
   }
   return 0;
}   

测试验证:

输入 a, b and c: 2.3
4
5.6
根是: -0.87+1.30i and -0.87-1.30i

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-12-07
亲,你的if-else没有加大括号,所以他没有包含属于他的全部语句,加上大括号
另外,在有两个不相等实根的时候输出函数中有两个参数,但是你只使用了一个%f,这个少了一个啊,还有共轭复根的地方不是这么表示的吧本回答被提问者和网友采纳
相似回答