大数
如果基本的整数和浮点数精度不能够满足需求,那么可以使用java.math包中两个很有用的类:BigInteger和BigDecimal。这两个类可以处理包含任意长度数字序列的数值。BigInteger类实现任意精度的整数运算,BigDecimal实现任意精度的浮点数运算。
使用静态的valueof方法可以将普通的数值转换为大数:- BigInteger a = BigInteger.valueOf(100);
复制代码 对于更大的数,可以使用一个带字符串参数的构造器:- BigInteger reallyBig = new BigInteger("134443493494321591498614658741974141641519614974168416516114914196419");
复制代码 另外还有一些常量:BigInteger.ZERO、BigInteger.ONE和BigInteger.TEN
注意:我们不能使用算术运算符(如:+和*)处理大数,而需要使用大叔类中的add和multiply方法。- BigInteger c = a.add(b); //c = a + b
- BigInteger d = c.multiply(b.add(BigInteger.valueOf(2))); //d = c * (b + 2)
复制代码 案例
假设你被邀请参加抽奖活动,并从500个可能的数值中抽取60个,下面程序会告诉你中彩的概率是多少
[code]import java.math.BigInteger;import java.util.Scanner;/** * @author JKC * @Description: * @date 2022/6/29 09:42 */public class SixSample { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("你需抽多少次?"); int k = in.nextInt(); System.out.println("你能抽的最高数是什么?"); int n = in.nextInt(); BigInteger lotteryOdds = BigInteger.valueOf(1); for (int i = 1; i |