Java常用类的使用:BigInteger、BigDecimal、Random。

Java常用类的使用:BigInteger、BigDecimal、Random。

  BigIntegerBigDecimalRandom是Java中常用的类,用于处理大整数高精度小数和生成随机数

1. BigInteger

用于表示任意精度的整数

常用方法

  • add(BigInteger val) : 将当前BigInteger与指定BigInteger相加。
  • multiply(BigInteger val) : 将当前BigInteger与指定BigInteger相乘。
  • subtract(BigInteger val) : 将当前BigInteger减去指定BigInteger。
  • divide(BigInteger val) : 将当前BigInteger除以指定BigInteger。

代码如下:

import java.math.BigInteger;

public class BigIntegerExample {
    public static void main(String[] args) {
        BigInteger num1 = new BigInteger("12345678901234567890");
        BigInteger num2 = new BigInteger("98765432109876543210");

        BigInteger sum = num1.add(num2);
        BigInteger product = num1.multiply(num2);

        System.out.println("Sum: " + sum);
        System.out.println("Product: " + product);
    }
}

2. BigDecimal

用于表示任意精度的小数。

常用方法:

  • add(BigDecimal val) : 将当前BigDecimal与指定BigDecimal相加。
  • multiply(BigDecimal val) : 将当前BigDecimal与指定BigDecimal相乘。
  • subtract(BigDecimal val) : 将当前BigDecimal减去指定BigDecimal。
  • divide(BigDecimal val) : 将当前BigDecimal除以指定BigDecimal。

代码如下:

import java.math.BigDecimal;

public class BigDecimalExample {
    public static void main(String[] args) {
        BigDecimal num1 = new BigDecimal("123.456");
        BigDecimal num2 = new BigDecimal("987.654");

        BigDecimal sum = num1.add(num2);
        BigDecimal product = num1.multiply(num2);

        System.out.println("Sum: " + sum);
        System.out.println("Product: " + product);
    }
}

3. Random

用于生成伪随机数。

常用方法:

  • nextInt(int bound) : 返回一个大于等于0且小于bound的随机整数。
  • nextDouble() : 返回一个0.0到1.0之间的随机双精度浮点数。

代码如下:

import java.util.Random;

public class RandomExample {
    public static void main(String[] args) {
        Random random = new Random();

        int randomInt = random.nextInt(100); // 生成0到99之间的随机整数
        double randomDouble = random.nextDouble(); // 生成0.0到1.0之间的随机双精度浮点数

        System.out.println("Random Integer: " + randomInt);
        System.out.println("Random Double: " + randomDouble);
    }
}



上一篇 Java——TreeMap、Properties的使用。
欢迎点赞、收藏、评论!!!
下一篇 java的变量类型大全。
  • 13
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值