有人可以检查一下我这个初学者 C 程序的算术吗?

发布于 2024-12-09 10:00:09 字数 525 浏览 0 评论 0原文

我正在用 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:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

谜兔 2024-12-16 10:00:10

x = (...) / (4 * a)

这不应该是 2 * a 吗?

x = (...) / (4 * a)

Shouldn't this be 2 * a?

孤独难免 2024-12-16 10:00:10

有趣的是,1.37(你得到的结果)大约是 2.73(你想要的结果)的一半,你瞧,它就在你的分母中,除以 4a 而不是 2a

就我个人而言,我会将该表达式写为:

x = (-b + sqrt (b * b - 4 * a * c)) / (2 * a);

因为它更接近于您尝试复制的方程(-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 of 2a.

Personally, I would write that expression as:

x = (-b + sqrt (b * b - 4 * a * c)) / (2 * a);

since it more closely matches the equation you're trying to duplicate (the -1 * b is better expressed as -b) and I find calling pow to get a simple square to be unnecessary where b * b does the same job without a function call.

写下不归期 2024-12-16 10:00:10

x1 = ((-1 * bcoeff) + (sqrt(pow(bcoeff, 2) - 4 * acoeff * ccoeff)))/(2 * acoeff);

x1 = ((-1 * bcoeff) + (sqrt(pow(bcoeff, 2) - 4 * acoeff * ccoeff)))/(2 * acoeff);

妥活 2024-12-16 10:00:10

在这里检查一下自己:.../(4 * acoeff)

Check yourself here: .../(4 * acoeff)

心头的小情儿 2024-12-16 10:00:10

虽然这个问题已经得到解答并指出了您的错误。我只想提一下,将问题分解为更多行会增加其可读性并可能减少所犯的错误。

float den = 2 * a;
float num1 = (-1 * b);
float num2 = pow(b ,2) - (4 * a * c);
float x = (num1 + sqrt(num2))/ den;

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.

float den = 2 * a;
float num1 = (-1 * b);
float num2 = pow(b ,2) - (4 * a * c);
float x = (num1 + sqrt(num2))/ den;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文