我有一个计算C中二次方程的根的任务,应该非常简单,我知道我需要对程序做什么,但我仍然遇到了问题.当根是虚构的并且平方根内的项为零时,它工作正常.
但是当我输入系数a,b和c时会产生真正的根,它给了我错误的答案,我无法弄清楚什么是错的.(我用a = 2,b = -5和c = 1测试它)
这是我的代码,它编译并运行,但给出了错误的答案.
#include<stdio.h>
#include<math.h>
int main()
{
float a, b, c, D, x, x1, x2, y, xi;
printf("Please enter a:\n");
scanf("%f", &a);
printf("Please enter b:\n");
scanf("%f",&b);
printf("Please enter c:\n");
scanf("%f", &c);
printf("The numbers you entered are: a = %f, b = %f, c = %f\n", a, b, c);
D = b*b-4.0*a*c;
printf("D = %f\n", D);
if(D > 0){
x1 = (-b + sqrt(D))/2*a;
x2 = ((-b) - sqrt(D))/2*a;
printf("The two real roots are x1=%fl and x2 = %fl\n", x1, x2);
}
if(D == 0){
x = (-b)/(2*a);
printf("There are two identical roots to this equation, the value of which is: %fl\n", x);
}
if (D<0){
y = sqrt(fabs(D))/(2*a);
xi = (-b)/(2*a);
printf("This equation has imaginary roots which are %fl +/- %fli, where i is the square root of -1.\n", xi, y);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
due*_*l0r 11
您没有正确计算结果:
x = y / 2*a
Run Code Online (Sandbox Code Playgroud)
实际上被解析为
x = (y / 2) * a
Run Code Online (Sandbox Code Playgroud)
所以你必须把括号括起来2*a.
你要这个:
x = y / (2 * a)
Run Code Online (Sandbox Code Playgroud)