美文网首页程序员
round、fix、floor、及 ceil 的取整方式

round、fix、floor、及 ceil 的取整方式

作者: geverway | 来源:发表于2017-05-01 17:22 被阅读105次

    round( )

    取最近的整数

        -2         -1          0          1          2
    -----|----------|----------|----------|----------|-----
                            取整方向
              ===<<==>>===================<<==>>===
    
    >> round(3.5)
    ans =  4
    >> round(-3.5)
    ans = -4
    >> round(3.1)
    ans =  3
    >> round(-3.1)
    ans = -3
    
    round(3.5) round(-3.5)
    4 -4
    round(3.1) round(-3.1)
    3 -3

    fix( )

    无论正负,舍去小数部分得到的整数

        -2         -1          0          1          2
    -----|----------|----------|----------|----------|-----
                            取整方向
                 ===>>===================<<===
    
    >> fix(3.5)
    ans =  3
    >> fix(-3.5)
    ans = -3
    >> fix(3.1)
    ans =  3
    >> fix(-3.1)
    ans = -3
    
    fix(3.5) fix(-3.5)
    3 -3
    fix(3.1) fix(-3.1)
    3 -3

    floor( )

    减去一个正小数到最近整数

        -2         -1          0          1          2
    -----|----------|----------|----------|----------|-----
               取整方向
         <<===================
    
    >> floor(3.5)
    ans =  3
    >> floor(-3.5)
    ans = -4
    >> floor(3.1)
    ans =  3
    >> floor(-3.1)
    ans =  -4
    
    floor(3.5) floor(-3.5)
    3 -4
    floor(3.1) floor(-3.1)
    3 4

    ceil( )

    加上一个正小数到最近整数

        -2         -1          0          1          2
    -----|----------|----------|----------|----------|-----
               取整方向
         ===================>>
    
    >> ceil(3.5)
    ans =  4
    >> ceil(-3.5)
    ans = -3
    >> ceil(3.1)
    ans =  4
    >> ceil(-3.1)
    ans = -3
    
    ceil(3.5) ceil(-3.5)
    4 -3
    ceil(3.1) ceil(-3.1)
    4 -3

    相关文章

      网友评论

        本文标题:round、fix、floor、及 ceil 的取整方式

        本文链接:https://www.haomeiwen.com/subject/csfqtxtx.html