溫馨提示×

java中如何取整

小億
81
2024-09-26 03:13:07
欄目: 編程語言

在Java中,可以使用以下幾種方法來進行取整操作:

  1. 使用Math.round()方法: Math.round()方法可以將浮點數(shù)四舍五入到最接近的整數(shù)。如果小數(shù)部分大于等于0.5,則向上取整;如果小數(shù)部分小于0.5,則向下取整。
double num = 3.6;
int roundedNum = (int) Math.round(num);
System.out.println("四舍五入后的整數(shù): " + roundedNum); // 輸出:四舍五入后的整數(shù): 4
  1. 使用Math.floor()方法: Math.floor()方法返回小于或等于給定參數(shù)的最大整數(shù)。對于負(fù)數(shù),它會返回更小的整數(shù)。
double num = 3.6;
int floorNum = (int) Math.floor(num);
System.out.println("向下取整后的整數(shù): " + floorNum); // 輸出:向下取整后的整數(shù): 3
  1. 使用Math.ceil()方法: Math.ceil()方法返回大于或等于給定參數(shù)的最小整數(shù)。對于負(fù)數(shù),它會返回更大的整數(shù)。
double num = 3.6;
int ceilNum = (int) Math.ceil(num);
System.out.println("向上取整后的整數(shù): " + ceilNum); // 輸出:向上取整后的整數(shù): 4
  1. 使用類型轉(zhuǎn)換: 通過將浮點數(shù)強制轉(zhuǎn)換為整數(shù),可以實現(xiàn)向下取整。這種方法不會進行四舍五入。
double num = 3.6;
int truncatedNum = (int) num;
System.out.println("向下取整后的整數(shù): " + truncatedNum); // 輸出:向下取整后的整數(shù): 3

注意:在使用類型轉(zhuǎn)換取整時,小數(shù)部分將被直接丟棄,可能導(dǎo)致精度損失。

0