繁体   English   中英

java.math.BigInteger的用法是错误的吗?

[英]Is java.math.BigInteger's usage wrong?

我玩java.math.BigInteger。 这是我的java类,

public class BigIntegerTest{
   public static void main(String[] args) {
     BigInteger fiveThousand = new BigInteger("5000");
     BigInteger fiftyThousand = new BigInteger("50000");
     BigInteger fiveHundredThousand = new BigInteger("500000");
     BigInteger total = BigInteger.ZERO;
     total.add(fiveThousand);
     total.add(fiftyThousand);
     total.add(fiveHundredThousand);
     System.out.println(total);
 }
}

我认为结果是555000 但实际是0 为什么?

BigInteger对象是不可变的。 一旦创建,它们的值就无法更改。

当您调用.add会创建并返回一个新的 BigInteger对象,如果要访问其值,则必须存储该对象。

BigInteger total = BigInteger.ZERO;
total = total.add(fiveThousand);
total = total.add(fiftyThousand);
total = total.add(fiveHundredThousand);
System.out.println(total);

(可以说total = total.add(...)因为它只是删除了对旧的 total对象的引用,并重新分配了对.add创建的引用的引用。

尝试这个

 BigInteger fiveThousand = new BigInteger("5000");
 BigInteger fiftyThousand = new BigInteger("50000");
 BigInteger fiveHundredThousand = new BigInteger("500000");
 BigInteger total = BigInteger.ZERO;

 total = total.add(fiveThousand).add(fiftyThousand).add(fiveHundredThousand);
 System.out.println(total);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM