CodeGym /Java 博客 /随机的 /整数除法Java
John Squirrels
第 41 级
San Francisco

整数除法Java

已在 随机的 群组中发布

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