四舍五入到最近的一百个

编程入门 行业动态 更新时间:2024-10-23 05:33:04
本文介绍了四舍五入到最近的一百个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我参与了我的java程序,在那里我需要四舍五入到最接近的百位并且认为可能有某种方法可以做到,但我猜不是。所以我搜索了网上的例子或任何答案,我还没有找到任何答案,因为所有的例子似乎都是近一百个。我只是想做这个并且向上舍入。也许有一些我忽略的简单解决方案。我已经尝试了 Math.ceil 和其他功能但尚未找到答案。如果有人可以帮我解决这个问题,我将非常感激。

I came to a part in my java program where I need to round up to the nearest hundred and thought that there was probably some way to do it but I guess not. So I searched the net for examples or any answers and I've yet to find any since all examples appear to be to the nearest hundred. I just want to do this and round UP. Maybe there's some simple solution that I'm overlooking. I have tried Math.ceil and other functions but have not found an answer as of yet. If anyone could help me with this issue I would greatly appreciate it.

如果我的数字是203,我希望结果四舍五入为300.你明白了。

If my number is 203, I want the result rounded to be 300. You get the point.

  • 801-> 900
  • 99-> 100
  • 14-> 100
  • 452-> 500
  • 801->900
  • 99->100
  • 14->100
  • 452->500
  • 推荐答案

    利用整数除法,它会截断商的小数部分。为了让它看起来像四舍五入,先添加99.

    Take advantage of integer division, which truncates the decimal portion of the quotient. To make it look like it's rounding up, add 99 first.

    int rounded = ((num + 99) / 100 ) * 100;

    示例:

    801: ((801 + 99) / 100) * 100 → 900 / 100 * 100 → 9 * 100 = 900 99 : ((99 + 99) / 100) * 100 → 198 / 100 * 100 → 1 * 100 = 100 14 : ((14 + 99) / 100) * 100 → 113 / 100 * 100 → 1 * 100 = 100 452: ((452 + 99) / 100) * 100 → 551 / 100 * 100 → 5 * 100 = 500 203: ((203 + 99) / 100) * 100 → 302 / 100 * 100 → 3 * 100 = 300 200: ((200 + 99) / 100) * 100 → 299 / 100 * 100 → 2 * 100 = 200

    相关的 Java语言规范引用,第15.17节.2 :

    整数除法向0舍入。也就是说,为操作数n和d生成的商二进制数字促销后的整数(§5.6.2)是一个整数值q,其大小尽可能大,同时满足| d·q | ≤| n |。

    Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| ≤ |n|.

    更多推荐

    四舍五入到最近的一百个

    本文发布于:2023-10-04 07:11:05,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1467133.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:一百个   四舍五入

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!