CodeGym /Java Blog /Toto sisi /整數除法Java
John Squirrels
等級 41
San Francisco

整數除法Java

在 Toto sisi 群組發布

Java中的整數除法是什麼?

Java 中的除法通常像數學或現實生活中的常規除法一樣發生。但是,它只是丟棄其餘部分。例如,如果您將 9 除以 2,則為 4,餘數為 1。 整數除法 Java - 1在現實生活中,答案為 4.5 或 4½。如果您在 Java 中使用 int 執行相同的計算,您的答案將是 4。它不會四捨五入到最接近的整數(如 ~4.5 = 5)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 數據類型來存儲四捨五入的商。

  • 給你!您將所需的輸出作為商。

結論

用 Java 整數除法一開始可能看起來很棘手。但是通過一些練習和重複,你可以掌握它。盡可能多地練習。隨時回到我們的帖子。乾杯! 為了鞏固您所學的知識,我們建議您觀看我們的 Java 課程中的視頻課程
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION