求解C中的ax^2+bx+c=0方程

Solving ax^2+bx+c=0 equation in C

我知道之前有人问过这个问题但是他们没有按照我的方式写程序或者我犯的错误。所以我们开始吧。

当我运行这个程序的时候,无论如何,它也打印出虚根。

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

  typedef struct tagComplex
  {
  double real;
  double imag;
  }Complex;

  void main(void)
  {
  SetConsoleTitle("Solve ax^2+bx+c=0");

  double a, b, c, delta;
  Complex x1, x2;
  char k = 'y';

  while(k == 'y')
  {
    printf("Enter the values of a, b, c: ");
    scanf("%lf%lf%lf", &a, &b, &c);
    while(getchar()!= '\n');

    delta = b*b - 4*a*c;
    if(delta > 0)                   //←-------- or delta > 1e-6 ?
    {
        x1.real = (-b + sqrt(delta))/(2*a);
        x2.real = (-b - sqrt(delta))/(2*a);

        printf("x1=%.3lf x2=%.3lf\n\n", x1.real, x2.real);
    }
    if(delta == 0)                 //←-------- or delta <= 1e-6 ? 
    {
        printf("x1=x2=%.3lf\n\n", -b/(2*a));
    }
    else
    {
       x1.real = -b/(2*a);
       x1.imag = sqrt(-delta)/(2*a);

       x2.real = -b/(2*a);
       x2.imag = -sqrt(-delta)/(2*a);

       printf("x1=%.3lf+%.3lf i x2=%.3lf+%.3lf i\n\n", x1.real, x1.imag, x2.real, x2.imag);
    }

    printf("Try another equation? (y or n)\n");
    scanf("%c", &k);
  }
}

我该如何解决?

Sample data: 1 -4 3

output:     
             x1=3.000 x2=1.000

             x1=2.000+-1.#IO i x2=2.000+1.#QO i

             Try another equation? (y or n)

目前您的分支显示

if(delta > 0) {
    // print two real roots
}
if(delta == 0) {
    // print single root
}
else {
    // print two complex roots
}

可以看到,如果delta > 0为真,那么delta == 0就会为假,执行到else分支。您还必须使 delta == 0 语句以 delta > 0 为条件。

也就是把if(delta == 0)换成else if(delta == 0).

Live example on Wandbox