在Java中,可以使用以下幾種方法進行取整操作:
Math.floor()
方法(向下取整):double number = 3.7;
int roundedDownNumber = (int) Math.floor(number);
System.out.println("向下取整結果: " + roundedDownNumber); // 輸出:3
Math.ceil()
方法(向上取整):double number = 3.7;
int roundedUpNumber = (int) Math.ceil(number);
System.out.println("向上取整結果: " + roundedUpNumber); // 輸出:4
Math.round()
方法(四舍五入取整):double number = 3.7;
int roundedNumber = (int) Math.round(number);
System.out.println("四舍五入取整結果: " + roundedNumber); // 輸出:4
int number = 3.7;
int roundedDownNumber = number - (int) number;
System.out.println("向下取整結果: " + roundedDownNumber); // 輸出:0
int number = 3.7;
int roundedUpNumber = (int) number + ((int) number > number ? 1 : 0);
System.out.println("向上取整結果: " + roundedUpNumber); // 輸出:4
根據你的需求選擇合適的方法進行取整操作。