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
     
     
  • 相关阅读:
    用C#开发.NET CF 蓝牙通信模块
    记录台湾民众生活:一起来看看台湾的物价
    .NET Socket开发之同步Socket实现两例
    SOA和BPM结合的三种方法
    Why we chose ASP.NET to run our startup
    用JScript.net写.net应用程序
    Linux至少有五大点比Vista更好
    Windows 窗体的.Net 框架绘图技术
    优化增强您的Visual C++应用程序
    VS 2008和.NET 3.5 Beta2新特性介绍
  • 原文地址:https://www.cnblogs.com/hanxue53/p/4315439.html
Copyright © 2011-2022 走看看