Java Math的floor、ceil、rint及round用法

36 篇文章 0 订阅

Java Math的floor、ceil、rint及round用法

先上程序运行结果,然后再分析原因

一、源程序

  1. public class Ceil_Floor_Round {
  2. public static void main(String[] args) {
  3. Scanner sc = new Scanner(System.in);
  4. while(sc.hasNext()){
  5. double num = sc.nextDouble();
  6. System.out.println( "Math.floor(" + num + ") = " + Math.floor(num));
  7. System.out.println( "Math.ceil(" + num + ") = " + Math.ceil(num));
  8. System.out.println( "Math.rint(" + num + ") = " + Math.rint(num));
  9. System.out.println( "Math.round(" + num + ") = " + Math.round(num));
  10. }
  11. }
  12. }

程序运行结果:


二、分析原因

1、Math.floor()向下取整,即小于这个数的最大的那个整数;

  1. Math.floor( 2.2) = 2.0;
  2. Math.floor( -2.2) = -3.0;
  3. Math.floor( 2.5) = 2.0;
  4. Math.floor( -2.5) = -3.0;
  5. Math.floor( 2.7) = 2.0;
  6. Math.floor( -2.7) = -3.0;

2、Math.ceil()向上取整,即大于这个数的最小的那个整数;

  1. Math.ceil( 2.2) = 3.0;
  2. Math.ceil( -2.2) = -2.0;
  3. Math.ceil( 2.5) = 3.0;
  4. Math.ceil( -2.5) = -2.0;
  5. Math.ceil( 2.7) = 3.0;
  6. Math.ceil( -2.7) = -2.0;

3、Math.rint()返回最接近该值的那个整数。注意如果存在两个这样的整数,则返回其中的偶数;

  1. Math.rint( 2.2) = 2.0
  2. Math.rint( -2.2) = -2.0
  3. Math.rint( 2.7) = 3.0
  4. Math.rint( -2.7) = -3.0
  5. Math.rint( 2.5) = 2.0
  6. Math.rint( -2.5) = -2.0
  7. Math.rint( 3.5) = 4.0
  8. Math.rint( -3.5) = -4.0

4、Math.round()“四舍五入”,但当参数为负数时不太好理解,直接上源码应该比较好理解。注意返回的是整型

Math.round(x) = Math.floor(x + 0.5)
  1. Math. round( 2.2) = 2
  2. Math. round( -2.2) = -2
  3. Math. round( 2.5) = 3
  4. Math. round( -2.5) = -2
  5. Math. round( 2.7) = 3
  6. Math. round( -2.7) = -3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值