Math.round()、ceil()和floor()

本文详细介绍了Java Math类中的取整方法,包括ceil(向上取整)、floor(向下取整)和round(四舍五入)。通过对不同数值的应用,展示了各方法的实现原理和结果,帮助读者深入理解Java中数值处理的细节。
摘要由CSDN通过智能技术生成

package java;

public class Test14 {
public static void main(String[] args) {
ceil();
floor();
round();
}

// 测试Math类的ceil方法(天花板,向上取整)
public static void ceil() {
	int a = (int) Math.ceil(11.3);// 12
	int b = (int) Math.ceil(-11.3);// -11

	System.out.println("a=" + a + ",b=" + b);
}

// 测试Math类的floor方法(地板,向下取整)
public static void floor() {
	int a = (int) Math.floor(11.6);// 11
	int b = (int) Math.floor(-11.6);// -12

	System.out.println("a=" + a + ",b=" + b);
}

// 测试Math类的round方法(四舍五入法)
public static void round() {
	int a = (int) Math.round(11.5);// 12  11.3+0.5  11
	int b = (int) Math.round(-11.5);// -11

	System.out.println("a=" + a + ",b=" + b);
}

}

  • 扩展:Math类中提供了三个与取整有关的方法:ceil、floor、round,这些方法的作用
  • 与它们的英文名称的含义相对应,例如,ceil的英文意义是天花板,该方法就表示向上取整,
  • 所以,Math.ceil(11.3)的结果为12,Math.ceil(-11.3)的结果是-11;floor的英
  • 文意义是地板,该方法就表示向下取整,所以,Math.floor(11.6)的结果为11,Math.floor(-11.6)
  • 的结果是-12;最难掌握的是round方法,它表示“四舍五入”,算法为Math.floor(x+0.5),即将原来的
  • 数字加上0.5后再向下取整,所以,Math.round(11.5)的结果为12,Math.round(-11.5)的结果为-11。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

健子bui

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值