JAVA基础知识——大数值

来源:互联网 发布:开票软件启动不了 编辑:程序博客网 时间:2024/05/20 02:52

大数值:

        java.math 类中有两个常用的类:BigInteger,BigDecimal

        BigInteger类实现了任意精度的整数运算,BigDecimal类实现了任意精度的浮点数运算

        使用静态的valueOf方法可以将普通的数值转换为大数值:BigInteger a = BigInteger.vslueOf(100);但不能使用+和*,而需要使用大数值中的add(加)、subtract(减)、multiply(乘)、divide(除)、mod(取余)方法    (将BigInteger该成BigDecimal,下面的方法就都可以使用了(用来计算浮点数运算))

        BigInteger c = a.add(b);   //c= a+b

          BigInteger d = c.multiply(b.add(BigInteger.valueOf(2)));  //d=c*(b+2)       

        BigInteger a = BigInteger.valueOf(4); //大数值
        BigInteger b = BigInteger.valueOf(5);


        BigInteger c = a.add(b); //加
        System.out.println(c); //9


        BigInteger d = a.multiply(b.add(a));//乘
        System.out.println(d); //36


        BigInteger q = b.subtract(a); //减
        System.out.println(q); //1


        BigInteger e = a.multiply(BigInteger.valueOf(2));
        System.out.println(e); //8


        BigInteger f = a.subtract(b);//减
        System.out.println(f); //-1


        BigInteger g = a.mod(b); //取余
        System.out.println(g); //4 


        int w = a.compareTo(b); //如果a=b,返回0  a<b,返回负数   a>b,返回整数
        System.out.println(w);  //-1

        

        BigInteger bi ;    //static BigInteger valueOf(long x)返回值等于x的大整数
        Long l = new Long(123456789L);
        bi = BigInteger.valueOf(l);
        String str = "BigInteger value of Long "+ l + "is" + bi;
        System.out.println(str);

0 0