Java中的整數除法是什麼?
Java 中的除法通常像數學或現實生活中的常規除法一樣發生。但是,它只是丟棄其餘部分。例如,如果您將 9 除以 2,則商為 4,餘數為 1。
示例 1 [ 餘數為 0 ]
Java 中的整數除法非常適用於除數完全除以被除數(整數除以 x 整數)的所有情況。答案是一個整數,整數數據類型可以容納它而不會溢出。因此沒有數據丟失。例如,看看下面的片段。
public class IntegerDivision {
public static void main(String[] args) {
int dividend = 100;
int divisor = 5;
int quotient = dividend / divisor;
//Dividend completely divides the divisor
System.out.println(dividend + " / " + divisor + " = " + quotient);
dividend = 143;
divisor = 11;
quotient = dividend / divisor;
//Dividend completely divides the divisor
System.out.println(dividend + " / " + divisor + " = " + quotient);
}
}
輸出
100 / 5 = 20 143 / 11 = 13
示例 2 [ 餘數不為 0 ]
對於餘數不為0的所有除法情況,最終結果將被截斷為最大可整除整數(9/2 = 4)。這將在即將到來的示例中展示。有時您可能需要十進制的實際商。對於這種情況,您可以使用 float 或 double 數據類型。但是,如果您希望將商四捨五入為最接近的整數,您可以執行以下操作。
public class IntegerDivision {
public static void main(String[] args) {
int dividend = 9;
int divisor = 2;
int quotient = dividend / divisor;
// Case I - Dividend does not divide the divisor completely
// The quotient is chopped / truncated
System.out.print("Integer division \t\t" );
System.out.println(dividend + " / " + divisor + " = " + quotient);
// Case II - Mathematical or real life division
// Use float or double data type to get the actual quotient
double actualQuotient = (double)dividend / divisor;
System.out.print("Mathematics division \t\t" );
System.out.println((double)dividend + " / " + divisor + " = " + actualQuotient);
// Case III - Integer Division with rounding off
// the quotient to the closest integer
long roundedQuotient = Math.round((double)dividend / divisor);
System.out.print("Round off int division \t\t" );
System.out.println((double)dividend + " / " + divisor + " = " + roundedQuotient);
}
}
輸出
整數除法 9 / 2 = 4 數學除法 9.0 / 2 = 4.5 四捨五入整數除法 9.0 / 2 = 5
解釋
案例 I 和案例 II 是不言自明的。對於 Case III,您可以按照以下步驟對其進行分解。-
首先,您需要將股息轉換為雙倍。
-
執行常規的 Java int 除法。
-
使用Math.round()方法對商進行四捨五入。
-
使用 long 數據類型來存儲四捨五入的商。
-
給你!您將所需的輸出作為商。
GO TO FULL VERSION