[英]Simple Multiplication and Arithmetic in C
I have an assignment to compute the roots of quadratic equations in C, should be pretty simple and I know what I need to do with the program but I am having a problem nonetheless. 我有一个计算C中二次方程的根的任务,应该非常简单,我知道我需要对程序做什么,但我仍然遇到了问题。 It works fine when the roots are imaginary and when the term inside the square root is zero.
当根是虚构的并且平方根内的项为零时,它工作正常。
But when I enter coefficients a, b and c which would give real roots it gives me the wrong answer, and I cant figure out whats wrong. 但是当我输入系数a,b和c时会产生真正的根,它给了我错误的答案,我无法弄清楚什么是错的。 (I am testing it with a=2, b = -5 and c=1)
(我用a = 2,b = -5和c = 1测试它)
This is my code, it compiles and runs, but gives the wrong answer. 这是我的代码,它编译并运行,但给出了错误的答案。
#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;
}
You don't calculate the result correctly: 您没有正确计算结果:
x = y / 2*a
is actually parsed as 实际上被解析为
x = (y / 2) * a
so you have to put parentheses around 2*a
. 所以你必须把括号括在
2*a
左右。
you want this: 你要这个:
x = y / (2 * a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.