使用 int 函数舍入到最低有效数字

发布于 2024-11-29 10:39:18 字数 294 浏览 2 评论 0原文

我的编程语言中没有舍入函数。我想获取浮点运算的结果,找到最低有效数字并据此进行舍入。到目前为止我在互联网上找到的都是只添加0.5的函数,这似乎非常不准确。

  1. 如何找到最低有效数字?
  2. 一旦我有了这个数字,我需要确定它是否> > 5或小于5。
  3. 如果它大于或等于5,那么我需要检查下一个数字,如果它大于5,则增加它,直到我到达小数点并对数字使用相同的确定(但作为一个整数,所以如果它是 65.444445 那么它应该是 66 我认为)小数点右边。至少这看起来是有道理的,但也许我把它复杂化了?

I don't have a rounding function in my programming language. I want to take the result of a floating point operation, find the least significant digit and round up based on that. What I've found so far on the Internet are functions that just add .5, which seems pretty inaccurate.

  1. How do I find the least significant digit?
  2. Once I have that digit, I need to determine if it is > 5 or less than 5.
  3. If it is greater than or equal to 5, then I need to check the next digit and increment it if it is greater than 5, till I get to the decimal point and use the same determination on the number (but as a whole number, so if it is 65.444445 then it should be 66 I think) to the right of the decimal place. At least this is what seems to make sense, but maybe I'm overcomplicating this?

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

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

发布评论

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

评论(1

晌融 2024-12-06 10:39:18

第一: 您和手头的问题决定有多少位有效数字。 最低有效数字就是最后一个有效数字。

第二:既然您知道如何四舍五入到最接近的整数,那么您可以通过将数字乘以之前的 10 次幂,然后乘以10 的倒数次方后。

例如,如果您决定应有 4 位有效数字,则最低有效数字是第四位数字。

数字 1234567890(10 位数字)可以通过以下方式舍入为该数字:

  • 乘以 10^-6,得到 1234.567890
  • 进行您发现的整数舍入,得到 1235
  • 乘以 10^6,得到 1235000000。

第三: 你把这个问题搞得太复杂了。 65.444445 比 66 更接近 65。它小于 65.5,即 65 和 66 之间的中点。

First: You and the problem at hand decide how many significant digits there are. The least significant digit is simply the last digit that's a significant digit.

Second: Since you know how to round to the nearest integer, then you can round to any significant digit by multiplying the number by a power of 10 before, and multiplying by the inverse power of 10 after.

If, for example, you have decided that there should be 4 significant digits, then the least significant digit is the fourth digit.

The number 1234567890 (10 digits) may be rounded to that digit by:

  • multiplying by 10^-6, giving 1234.567890
  • doing the integer round that you've discovered, giving 1235
  • multiplying by 10^6, giving 1235000000.

Third: You're overcomplicating this. 65.444445 is closer to 65 than it is to 66. It's less than 65.5, which is the midpoint between 65 and 66.

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