使用JavaScript将数字四舍五入到5的下一个整数

2021年3月20日17:15:49 发表评论 728 次浏览

给定一个正整数n, 任务是将数字四舍五入到可以除以5的下一个整数。

例子:

Input : 46 
Output : 50

Input : 21
Output : 25

Input : 30 
Output : 30

方法1:

  • 将数字放入变量中。
  • 用5除以得到十进制值。
  • 通过使用取小数的ceil值math.ceil().
  • 将其乘以5即可得到结果。
<script>
     function round(x) {
         return Math.ceil(x / 5) * 5;
     }
  
var n = 34;
console.log(round(n)); 
</script>

输出如下:

35

方法二:

  • 将数字放入变量中。
  • 如果可以被5整除, 则返回相同的数字。
  • 否则, 将其除以5, 取下限, 然后再次将其乘以5, 再加上5。
<script>
     function round(x) {
         if (x % 5 == 0) {
             return int(Math.floor(x / 5)) * 5;
         } else {
             return (int(Math.floor(x / 5)) * 5) + 5;
         }
     }
  
var n = 34;
console.log(round(n)); 
</script>

输出如下:

35

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: