dln*_*385 2 java math methods function
给定整数 'a' 和 'b',我想要一个返回 a / b 的下限和余数的方法,这样:
例如,5/3 = 1 + 2/3。
a这是仅适用于 正和的尝试b:
public static long[] floorAndRemainder(long a, long b) {
long floor = a / b;
long remainder = a % b;
return new long[] { floor, remainder };
}
Run Code Online (Sandbox Code Playgroud)
我需要一个适用于所有正负分子和分母的函数。例如,
-5/3 = -2 + 1/35/-3 = -2 + 1/3-5/-3 = 1 + 2/3使用浮点数学来简化逻辑。请注意,由于精度损失,这会导致大量数据产生不正确的结果。
public static long[] floorAndRemainder(long a, long b) {
long floor = (long) Math.floor(a / (double) b);
long remainder = Math.abs(a - floor * b);
return new long[] { floor, remainder };
}
Run Code Online (Sandbox Code Playgroud)
使用整数除法和模运算符求取下限和余数,然后纠正负分数。这表明在不使用地板的情况下,余数是相对难以纠正的。
public static long[] floorAndRemainder(long a, long b) {
long floor = a / b;
long remainder = a % b;
boolean isNegative = a < 0 ^ b < 0;
boolean hasRemainder = remainder != 0;
// Correct the floor.
if (isNegative && hasRemainder) {
floor--;
}
// Correct the remainder.
if (hasRemainder) {
if (isNegative) {
if (a < 0) { // then remainder < 0 and b > 0
remainder += b;
} else { // then remainder > 0 and b < 0
remainder = -remainder - b;
}
} else {
if (remainder < 0) {
remainder = -remainder;
}
}
}
return new long[] { floor, remainder };
}
Run Code Online (Sandbox Code Playgroud)
以与实现 2 相同的方式查找下限,然后像实现 1 一样使用该下限查找余数。
public static long[] floorAndRemainder(long a, long b) {
long floor = a / b;
if ((a < 0 ^ b < 0) && a % b != 0) {
floor--;
}
long remainder = Math.abs(a - floor * b);
return new long[] { floor, remainder };
}
Run Code Online (Sandbox Code Playgroud)