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