Java番石榴 | IntMath 类的 sqrt(int x, RoundingMode mode) 方法
Guava 的 IntMath 类的方法sqrt(int x, RoundingMode mode)返回 x 的平方根,用指定的舍入模式四舍五入。
句法:
public static int sqrt(int x, RoundingMode mode)
例外:
- IllegalArgumentException:如果 x < 0。
- ArithmeticException:如果模式是 RoundingMode.UNNECESSARY 并且 sqrt(x) 不是整数。
枚举舍入模式
Enum Constant | Description |
---|---|
CEILING | Rounding mode to round towards positive infinity. |
DOWN | Rounding mode to round towards zero. |
FLOOR | Rounding mode to round towards negative infinity. |
HALF_DOWN | Rounding mode to round towards “nearest neighbor” unless both neighbors are equidistant, in which case round down. |
HALF_EVEN | Rounding mode to round towards the “nearest neighbor” unless both neighbors are equidistant, in which case, round towards the even neighbor. |
HALF_UP | Rounding mode to round towards “nearest neighbor” unless both neighbors are equidistant, in which case round up. |
UNNECESSARY | Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary. |
UP | Rounding mode to round away from zero. |
下面给出了一些示例,以更好地理解实现:
示例 1:
// Java code to show implementation of
// sqrt(int x, RoundingMode mode) method
// of Guava's IntMath class
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
// Driver code
public static void main(String args[])
{
int x1 = 226;
// Using sqrt(int x, RoundingMode mode)
// method of Guava's IntMath class
// The RoundingMode HALF_EVEN rounds towards
// the nearest neighbor unless both neighbors
// are equidistant, in which case, round towards
// the even neighbor.
int ans1 = IntMath.sqrt(x1,
RoundingMode.HALF_EVEN);
System.out.println("Square root of x1 is: "
+ ans1);
int x2 = 154;
// Using sqrt(int x, RoundingMode mode)
// method of Guava's IntMath class
// The RoundingMode FLOOR rounds towards
// negative infinity.
int ans2 = IntMath.sqrt(x2,
RoundingMode.FLOOR);
System.out.println("Square root of x2 is: "
+ ans2);
}
}
输出:
Square root of x1 is: 15
Square root of x2 is: 12
示例 2:
// Java code to show implementation of
// sqrt(int x, RoundingMode mode) method
// of Guava's IntMath class
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
// Driver code
public static void main(String args[])
{
int x1 = -65;
try {
// Using sqrt(int x, RoundingMode mode)
// method of Guava's IntMath class
// The RoundingMode HALF_EVEN rounds towards
// the nearest neighbor unless both neighbors
// are equidistant, in which case, round towards
// the even neighbor.
// This should throw "IllegalArgumentException"
// as x1 < 0
int ans1 = IntMath.sqrt(x1,
RoundingMode.HALF_EVEN);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
java.lang.IllegalArgumentException: x (-65) must be >= 0
参考:
https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/IntMath.html#sqrt-int-java.math.RoundingMode-