sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Java取余和取整
在Java中,取余和取整是常见的数学操作。下面分别介绍如何进行这两种操作。

取余(Modulus)

取余操作通常使用 % 运算符。% 运算符返回两个数相除的余数。

示例代码:

int result = 10 % 3; // 结果是 1
System.out.println(result); // 输出:1
取整(Floor, Ceiling, Round)

对于取整操作,Java提供了Math类中的几个方法,包括floor(), ceil(), 和 round(),这些方法可以用来处理不同类型的取整需求。

floor():返回小于或等于参数的最大整数(向下取整)。

ceil():返回大于或等于参数的最小整数(向上取整)。

round():返回最接近参数的整数,当参数的绝对值是0.5时,结果是偶数。

示例代码:

double d = 9.7;
double d2 = -9.7;

// floor()
System.out.println(Math.floor(d)); // 输出:9.0
System.out.println(Math.floor(d2)); // 输出:-10.0

// ceil()
System.out.println(Math.ceil(d)); // 输出:10.0
System.out.println(Math.ceil(d2)); // 输出:-9.0

// round()
System.out.println(Math.round(d)); // 输出:10,四舍五入到最近的整数
System.out.println(Math.round(d2)); // 输出:-10,四舍五入到最近的整数
注意点

当使用%运算符时,确保第一个操作数是整数类型或者至少一个是整数类型,否则会进行浮点除法并返回浮点数类型的余数。

使用Math.floor(), Math.ceil(), 和 Math.round()时,参数可以是int, long, float, 或 double类型。返回的结果类型与参数的类型相同,除非特别指定(例如使用(int)强制类型转换)。

对于Math.round()方法,如果要得到一个整数结果,并且原始数是浮点数,通常需要将结果强制类型转换为int或long。例如:int result = (int) Math.round(d);。

这些是在Java中进行取余和取整的基本方法。

posted on 2025-07-28 15:09  sunny123456  阅读(193)  评论(0)    收藏  举报