java面试题网

普通会员

483

帖子

9

回复

187

积分

楼主
发表于 2019-08-26 15:24:39 | 查看: 5047| 回复: 0

Guava LongMath类

Guava LongMath类

LongMath提供long基础类型的实用方法。

类声明

以下是com.google.common.math.LongMath类的声明:

@GwtCompatible(emulated=true)
public final class LongMath
   extends Object

方法

Guava LongMath类_www.wityx.com

方法继承

这个类继承了以下类方法:

java.lang.Object

LongMath 示例

使用所选择的任何编辑器创建下面的java程序 C:/> Guava GuavaTester.java

import java.math.RoundingMode;
import com.google.common.math.LongMath;

public class GuavaTester {

   public static void main(String args[]){
      GuavaTester tester = new GuavaTester();
      tester.testLongMath();
   }

   private void testLongMath(){
      try{
         System.out.println(LongMath.checkedAdd(Long.MAX_VALUE, Long.MAX_VALUE));
      }catch(ArithmeticException e){
         System.out.println("Error: " + e.getMessage());
      }

      System.out.println(LongMath.divide(100, 5, RoundingMode.UNNECESSARY));
      try{
         //exception will be thrown as 100 is not completely divisible by 3 thus rounding
         // is required, and RoundingMode is set as UNNESSARY
         System.out.println(LongMath.divide(100, 3, RoundingMode.UNNECESSARY));
      }catch(ArithmeticException e){
         System.out.println("Error: " + e.getMessage());
      }

      System.out.println("Log2(2): "+LongMath.log2(2, RoundingMode.HALF_EVEN));

      System.out.println("Log10(10): "+LongMath.log10(10, RoundingMode.HALF_EVEN));

      System.out.println("sqrt(100): "+LongMath.sqrt(LongMath.pow(10,2), RoundingMode.HALF_EVEN));

      System.out.println("gcd(100,50): "+LongMath.gcd(100,50));

      System.out.println("modulus(100,50): "+LongMath.mod(100,50));

      System.out.println("factorial(5): "+LongMath.factorial(5));
   }
}

验证结果

使用javac编译器编译如下类

C:Guava>javac GuavaTester.java

现在运行GuavaTester看到的结果

C:Guava>java GuavaTester

看到结果

Error: overflow
20
Error: mode was UNNECESSARY, but rounding was necessary
Log2(2): 1
Log10(10): 1
sqrt(100): 10
gcd(100,50): 50
modulus(100,50): 0
factorial(5): 120


文章来自www.wityx.com,转载请注明出处!原文地址http://www.wityx.com/post/1271_1_1.html

上一篇:Guava BigIntegerMath类 下一篇:Guava IntMath类
您需要登录后才可以回帖 登录 | 立即注册

java面试题网www.wuliaokankan.cnjava建站系统提供技术支持V2.1 网站地图 © 2016-2018