21xrx.com
2024-04-25 14:18:18 Thursday
登录
文章检索 我的文章 写文章
求二次方程根的C程序
2021-07-06 21:07:05 深夜i     --     --
C

求二次方程根的 C 程序:假设系数为整数,但根可能是实数,也可能不是实数。

对于二次方程 ax2+ bx + c = 0 (a≠0),判别式 (b2-4ac) 决定根的性质。 如果它小于零,根是虚数,或者如果它大于零,根是实数。 如果为零,则根相等。

对于二次方程,其根之和 = -b/a 和其根之积 = c/a。 现在让我们编写程序。

 

C中二次方程的根

#include <stdio.h>
#include <math.h>


int main()
{
  int a, b, c, d;
  double root1, root2;

  printf("Enter a, b and c where a*x*x + b*x + c = 0\n");
  scanf("%d%d%d", &a, &b, &c);

  d = b*b - 4*a*c;

  if (d < 0) { // complex roots, i is for iota (√-1, square root of -1)
    printf("First root = %.2lf + i%.2lf\n", -b/(double)(2*a), sqrt(-d)/(2*a));
    printf("Second root = %.2lf - i%.2lf\n", -b/(double)(2*a), sqrt(-d)/(2*a));
  }
  else { // real roots
    root1 = (-b + sqrt(d))/(2*a);
    root2 = (-b - sqrt(d))/(2*a);

    printf("First root = %.2lf\n", root1);
    printf("Second root = %.2lf\n", root2);
  }

  return 0;
}

 

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复