Guava – IntMath.log10()方法及实例
Guava的IntMath类的log10(int x, RoundingMode mode)方法接受两个参数,并根据第二个参数指定的舍入模式计算第一个参数的基10对数值。
语法:
public static int log10(int x, RoundingMode mode)
参数: 该方法需要2个参数。
x 是要找到的int值的记录。mode 是指定的四舍五入模式。返回值 : 该方法返回x的BASE-10对数,根据指定的四舍五入模式进行舍入。
异常情况: 该方法抛出以下参数。
IllegalArgumentException:如果值x是0或负值。ArithmeticException:如果模式是RoundingMode.UNNECESSARY并且x不是10的幂。Enum RoundingMode
| Enum 常数 | 描述 |
|---|---|
| CEILING | 四舍五入模式,向正无穷大方向取舍。 |
| DOWN | 四舍五入模式,向零舍去。 |
| FLOOR | 四舍五入模式,向负无穷值方向取舍。 |
| HALF_DOWN | 四舍五入的模式是向 “最近的邻居 “四舍五入,除非两个邻居的距离相等,在这种情况下四舍五入。 |
| HALF_EVEN | 四舍五入模式是向 “最近的邻居 “四舍五入,除非两个邻居的距离相等,在这种情况下,向偶数邻居四舍五入。 |
| HALF_UP | 四舍五入的模式是向 “最近的邻居 “四舍五入,除非两个邻居的距离相等,在这种情况下四舍五入。 |
| UNNECESSARY | 四舍五入模式,断言请求的操作有一个精确的结果,因此不需要四舍五入。 |
| UP | 四舍五入模式,从零开始取舍。 |
下面给出了一些例子,以更好地理解实现。
例1 :
// Java code to show implementation of// log10(int x, RoundingMode mode) method// of Guava's IntMath classimport java.math.RoundingMode;import com.google.common.math.IntMath; class GFG { // Driver code public static void main(String args[]) { int a1 = 10000; // Using log10(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. System.out.println( IntMath.log10(a1, RoundingMode.HALF_EVEN)); int a2 = 15; // Using log10(int x, RoundingMode mode) // method of Guava's IntMath class // The RoundingMode HALF_DOWN rounds towards // "nearest neighbor" unless both neighbors // are equidistant, in which case round down. System.out.println( IntMath.log10(a2, RoundingMode.HALF_DOWN)); }}
输出:
41
例2 :
// Java code to show implementation of// log10(int x, RoundingMode mode) method// of Guava's IntMath classimport java.math.RoundingMode;import com.google.common.math.IntMath; class GFG { static int findlog10(int x, RoundingMode mode) { try { // Using log10(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 x <= 0 int ans = IntMath.log10(x, mode); // Return the answer return ans; } catch (Exception e) { System.out.println(e); return -1; } } // Driver code public static void main(String args[]) { int x = -152; try { // Function calling findlog10(x, RoundingMode.HALF_EVEN); } catch (Exception e) { System.out.println(e); } }}输出:
java.lang.IllegalArgumentException: x (-152) must be > 0
参考资料:
https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/IntMath.html#log10-int-java.math.RoundingMode-
