有人可以检查一下我这个初学者 C 程序的算术吗?
我正在用 C 编写一个程序来计算以下公式:
(来源:crewtonramoneshouseofmath.com)
这是行代码(我只是使用+而不是+-):
x = ((-1 * b) + (sqrt(pow(b, 2) - 4 * a * c)))/(4 * a);
我没有得到正确的根。例如,如果 a = 1、b=-2 和 c=-2,则它应该为 2.73。相反,我得到的是 1.37。
一直盯着代码,我没有看到错误。有人可以帮我指出吗?
I am writing a program in C that calculates this formula:
(source: crewtonramoneshouseofmath.com)
here is the line of code (I am just using + instead of the +-):
x = ((-1 * b) + (sqrt(pow(b, 2) - 4 * a * c)))/(4 * a);
I am not getting the correct root. For example if a = 1, b=-2, and c=-2 it SHOULD be 2.73. Instead I am getting 1.37.
Been staring at the code and I don't see the mistake. Can someone point it out for me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
x = (...) / (4 * a)
这不应该是
2 * a
吗?x = (...) / (4 * a)
Shouldn't this be
2 * a
?有趣的是,1.37(你得到的结果)大约是 2.73(你想要的结果)的一半,你瞧,它就在你的分母中,除以
4a
而不是2a
。就我个人而言,我会将该表达式写为:
因为它更接近于您尝试复制的方程(
-1 * b
更好地表示为-b
)并且我发现调用pow
来获得一个简单的正方形是不必要的,而b * b
在没有函数调用的情况下完成相同的工作。It's interesting that 1.37 (what you're getting) is about half of 2.73 (what you want) and, lo and behold, there it is in your denominator, dividing by
4a
instead of2a
.Personally, I would write that expression as:
since it more closely matches the equation you're trying to duplicate (the
-1 * b
is better expressed as-b
) and I find callingpow
to get a simple square to be unnecessary whereb * b
does the same job without a function call.x1 = ((-1 * bcoeff) + (sqrt(pow(bcoeff, 2) - 4 * acoeff * ccoeff)))/(2 * acoeff);
x1 = ((-1 * bcoeff) + (sqrt(pow(bcoeff, 2) - 4 * acoeff * ccoeff)))/(2 * acoeff);
在这里检查一下自己:
.../(4 * acoeff)
Check yourself here:
.../(4 * acoeff)
虽然这个问题已经得到解答并指出了您的错误。我只想提一下,将问题分解为更多行会增加其可读性并可能减少所犯的错误。
While this question has already been answered and your error pointed out. I would just like to mention that breaking the problem down into more lines would increase its readability and potentially reduce mistakes made.