zoukankan      html  css  js  c++  java
  • java中的三种取整函数

    1.Math.floor

    floor,英文原意:地板。 
    Math.floor 函数是求一个浮点数的地板,就是 向下 求一个最接近它的整数,它的值肯定会小于或等于这个浮点数。

    Math.floor(-1.1): -2.0 
    Math.floor(-1.5): -2.0 
    Math.floor(-1.6): -2.0 
    Math.floor(0.1): 0.0 
    Math.floor(0.5): 0.0 
    Math.floor(0.6): 0.0 
    Math.floor(1.1): 1.0 
    Math.floor(11.5): 11.0 
    Math.floor(15.7): 15.0

    Math.floor(-0.5): -0.0 

    2.Math.ceil

    ceil,英文原意:天花板。 
    Math.ceil 函数执行的是 向上 取接近的整数,它返回的肯定会大于或等于函数参数。

    Math.ceil(-1.1): -1.0 
    Math.ceil(-1.5): -1.0 
    Math.ceil(-1.6): -1.0 
    Math.ceil(0.1): 1.0 
    Math.ceil(0.5): 1.0 
    Math.ceil(0.6): 1.0 
    Math.ceil(1.1): 2.0 
    Math.ceil(1.5): 2.0 
    Math.ceil(1.6): 2.0 

    Math.ceil(-0.5): -1.0

    3.Math.rint

    Math.rint 函数返回最接近参数的整数,如果有2个数同样接近,则会返回偶数的那个。

    Math.rint(-1.1): -1.0 
    Math.rint(-1.5): -2.0 
    Math.rint(-1.6): -2.0 
    Math.rint(0.1): 0.0 
    Math.rint(0.5): 0.0 
    Math.rint(0.6): 1.0 
    Math.rint(1.1): 1.0 
    Math.rint(1.5): 2.0 
    Math.rint(1.6): 2.0

    4.Math.round

    round 方法,我们通常会说这个方法表示”四舍五入”,但是当参数为负数时,就不太好理解。 

    所以,以源码的计算方式来理解会比较准确。

    即将原来的数字加上0.5后再向下取整。 

    源码大意:

    Math.round(x) = Math.floor(x + 0.5)

    Math.round(-1.1): -1 
    Math.round(-1.5): -1 
    Math.round(-1.6): -2 
    Math.round(0.1): 0 
    Math.round(0.5): 1 
    Math.round(0.6): 1 
    Math.round(1.1): 1 
    Math.round(1.5): 2 
    Math.round(1.6): 2

  • 相关阅读:
    DataGridView 鼠标双击获得行列索引
    浅谈MVC、MVP、MVVM架构模式的区别和联系
    Codeforces 336D Dima and Trap Graph 并查集
    Codeforces 601C Kleofáš and the n-thlon 概率dp
    Codeforces 311B Cats Transport 斜率优化dp
    Codeforces 908F New Year and Rainbow Roads
    Codeforces 12D Ball cdq分治
    Codeforces 291 E Tree-String Problem AC自动机
    Codeforces 932E Team Work 数学
    Codeforces 463E Caisa and Tree
  • 原文地址:https://www.cnblogs.com/Eason-S/p/5391581.html
Copyright © 2011-2022 走看看