Objective C - iOS - 奇怪的 fmod() 行为

发布于 2024-11-26 17:50:28 字数 275 浏览 2 评论 0原文

有人可以帮我解释以下内容吗?您可以在 Google 中输入相同的数字,并得到与我在代码中得到的相同的结果...

1089.80 % 0.04 = 0
1089.84 % 0.04 = 0.04 - Surely this is wrong? 0.04 goes into 1089.84 with no remainder.
1089.88 % 0.04 = 0
1089.92 % 0.04 = 0

其他看似正确的数字也会出现类似的行为。

提前致谢!

Can anybody help me explain the following? You can type the same numbers into Google and get the same results as I am getting in code....

1089.80 % 0.04 = 0
1089.84 % 0.04 = 0.04 - Surely this is wrong? 0.04 goes into 1089.84 with no remainder.
1089.88 % 0.04 = 0
1089.92 % 0.04 = 0

Similar behaviour appears for other numbers that should seemingly be correct.

Thanks in advance!

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

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

发布评论

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

评论(2

原来分手还会想你 2024-12-03 17:50:28

您正在查看四舍五入的值。在内部,该数字不是 1089.84,而是类似 1089.84000026。

如果您想要“正确”的值,请将两边乘以 100,再加上 0.5,然后对它们进行 (int),然后取整数 mod,并将结果转换回浮点型。

You're looking at the rounded values. Internally the number is not 1089.84 but something like 1089.84000026.

If you want "correct" values, multiply both sides by 100, add 0.5, and (int) them, then take the integer mod, and convert the result back to float.

忘你却要生生世世 2024-12-03 17:50:28

事实上,1089.84 等于 0.04,没有余数。然而,这并不是您要求计算机为您执行的计算。

1089.84 和 0.04 都不能表示为浮点数。因此,每个双精度文字都会四舍五入到最接近的可表示值。您实际计算的是:

1089.839999999999918145476840436458587646484375 % 0.040000000000000000832667268468867405317723751068115234375

正是

0.039999999999895459457111002166129765100777149200439453125

在打印结果时,它被四舍五入到小数点后几位以供显示,因此您看到的是 0.04。

Indeed, 0.04 goes into 1089.84 with no remainder. However, that is not the computation that you are asking the computer to perform for you.

Neither 1089.84 nor 0.04 is representable as a floating point number. Thus, each of the double-precision literals is rounded to the closest representable value. What you are actually computing is:

1089.839999999999918145476840436458587646484375 % 0.040000000000000000832667268468867405317723751068115234375

which is precisely

0.039999999999895459457111002166129765100777149200439453125

when you print the result, it is being rounded to a few decimal places for display, and so you see 0.04.

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