1. 程式人生 > >Java取整函式的使用

Java取整函式的使用

在開發中,取整操作使用是很普遍的,所以Java在Math類中添加了數字取整方法。在Math類中主要包括以下幾種取整方法。

public static double ceil(double a):返回大於等於引數的最小整數。

public static double floor(double a):返回小於等於引數的最大整數。

public static double rint(double a):返回與引數最接近的整數,如果兩個同為整數且同樣接近,則結果取偶數。

public static int round(float a):將引數加上0.5後返回與引數最近的整數。

public static long round(double a):將引數加上0.5後返回與引數最近的整數,然後強制轉換為長整型。

下面舉例說明Math類中取整方法的使用。

public static void main(String args[])
{
	// 返回第一個大於等於引數的整數
	System.out.println("使用ceil()方法取整:" + Math.ceil(5.2));

	// 返回第一個小於等於引數的整數
	System.out.println("使用floor()方法取整:" + Math.floor(2.5));

	// 返回與引數最接近的整數
	System.out.println("使用rint()方法取整:" + Math.rint(2.7));

	// 返回與引數最接近的整數
	System.out.println("使用rint()方法取整:" + Math.rint(2.5));

	// 將引數加上0.5後返回最接近的整數
	System.out.println("使用round()方法取整:" + Math.round(3.4f));

	// 將引數加上0.5後返回最接近的整數,並將結果強制轉換為長整型
	System.out.println("使用round()方法取整:" + Math.round(2.5));
}

執行結果:

使用ceil()方法取整:6.0
使用floor()方法取整:2.0
使用rint()方法取整:3.0
使用rint()方法取整:2.0
使用round()方法取整:3
使用round()方法取整:3