zoukankan      html  css  js  c++  java
  • java的四种取整方法

    java 中取整操作提供了四种方法:分别是: 

    public static double ceil(double a)//向上取整

     public static double floor(double a)//向下取整
     public static long round(double a)//四舍五入取整
     public static double rint(double a)//最近取整
     
     

     第一种:ceil是天花板的意思,表示向上取整。   测试: 

    System.out.println(Math.ceil(1.01));
    System.out.println(Math.ceil(-1.01));
    System.out.println(Math.ceil(1.5));
    System.out.println(Math.ceil(-1.5));
     
     

    输出结果: 

    2.0
    -1.0
    2.0
    -1.0
     
     

     第二种:floor是地板的意思,表示向下取整。   测试: 

    System.out.println(Math.floor(1.01));

    System.out.println(Math.floor(-1.01));
    System.out.println(Math.floor(1.5));
    System.out.println(Math.floor(-1.5));
     
     

     输出: 

    1.0

    -2.0
    1.0
    -2.0
     
     

     第三种:round执行的就是数学上的四舍五入运行。   查看它源码可知其与floor方法的关系: 

    public static long round(double a) {
    return (long)floor(a + 0.5d);
        }
     
     

    测试: 

    System.out.println(Math.round(-1.5));
    System.out.println(Math.round(1.5));
    结果:
    -1
    2
     
     

    第四种:最有意思的,返回最接近参数的整数,如果有2个数同样接近,则返回偶数的那个。它有两个特殊的情况:

    1)如果参数本身是整数,则返回本身。

    2)如果不是数字或无穷大或正负0,则结果为其本身。 

    Returns the double value that is closest in value to the argument and is equal to a mathematical integer. If two double values that are mathematical integers are equally close, the result is the integer value that is even. Special cases:  
    If the argument value is already equal to a mathematical integer, then the result is the same as the argument.  

    If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument. 

    Parameters:  a a double value. 

    Returns:  the closest floating-point value to a that is equal to a mathematical integer. 
    测试: 

    System.out.println(Math.rint(-1.5));
    System.out.println(Math.rint(1.5));
    System.out.println(Math.rint(-2.5));
    System.out.println(Math.rint(2.5));
    结果:
    -2.0
    2.0
    -2.0
    2.0
     
     
  • 相关阅读:
    android的NDK和java进行本地socket通信
    Android 8款开源游戏引擎
    Android使用AndEngine创建第一个程序
    J2ME项目移植到Android平台六大注意事项
    面面具到!android重力传感器
    android应用程序的混淆打包
    Android 5.0最应该实现的8个期望
    android service 的各种用法(IPC、AIDL)
    Android上怎样使用《贝赛尔曲线》
    Java序列化与反序列化学习(二):序列化接口说明
  • 原文地址:https://www.cnblogs.com/hanxue53/p/4315439.html
Copyright © 2011-2022 走看看