我知道有人在之前问过这个问题,但是 他们没有按照我的方式编写程序或犯了我的错误。所以我们开始吧。
当我运行程序时,无论如何,它也会打印出假想的根。
#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)
答案 0 :(得分:4)
当前您的分支机构读取
if(delta > 0) {
// print two real roots
}
if(delta == 0) {
// print single root
}
else {
// print two complex roots
}
如您所见,如果delta > 0
为true,则delta == 0
为false,执行将转到else分支。您还必须以delta == 0
为条件的delta > 0
语句。
也就是说,将if(delta == 0)
替换为else if(delta == 0)
。