C 编程 double 和 int 加法

发布于 2025-01-12 16:54:58 字数 1468 浏览 3 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

软的没边 2025-01-19 16:54:58

我一直在尝试 array[*level]++;array[*level] += 1.00;,但是当我使用print,为什么它总是返回 0.988889999 或者不是 1.000000 的东西?

因为增量之前的值并不正好是0.0。您没有向我们提供足够的信息来评估原因。可能是这样。

假设 IEEE-754 浮点算术(这是一个非常安全的假设),浮点加法(其中操作数和数学结果都可以精确地以浮点格式表示)会产生精确结果的表示。

如果您希望数组的元素始终具有整数值,那么您可能应该使用整数元素类型。如果您选择 double 作为其可表示值的范围,那么您可能会搬起石头砸自己的脚,因为相对于整数类型增加的范围是以有限的精度为代价的。如果您需要表示大于 unsigned long long int 可以表示的精确整数,那么您需要一个任意精度的数学库,例如 GMP

I kept trying array[*level]++; or array[*level] += 1.00;, but when I check the current double in the array using print, why does it always return 0.988889999 or something that's not 1.000000?

Because the value before the increment was not exactly 0.0. You have not given us enough information to evaluate why that might be.

Assuming IEEE-754 floating-point arithmetic (which is a pretty safe assumption), floating-point additions where the operands and the mathematical result are all exactly representable in the floating point format produce a representation of the exact result.

If you expect the elements of your array always to have integer values, then you probably should use an integer element type. If you chose double for its range of representable values then you may have shot yourself in the foot, because the increased range relative to integer types comes at the cost of limited precision. If you need to represent exact integers larger than unsigned long long int can represent then you need an arbitrary-precision math library such as GMP.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文