【问题标题】:BigInteger returning negative numbers [duplicate]BigInteger 返回负数 [重复]
【发布时间】:2014-06-14 19:21:05
【问题描述】:

为什么这个数学对某些数字返回负数:

int x = 351;

    String bigValue= ((50*x*x*x-150*x*x+400*x)/3) + "";
    BigInteger resultInteger = new BigInteger(bigValue);
    System.out.println(resultInteger);

结果 -> 714612600

但如果我使用 352

结果 -> -710900565

对于 x=500 -> 639244234

为什么?

【问题讨论】:

  • 您正在乘以和除以在某些时候会溢出的整数。

标签: java math biginteger


【解决方案1】:

这里的这一行:

(50*x*x*x-150*x*x+400*x)/3

正在使用整数,可能会溢出。如果一个整数达到最大值 (2^31-1),它将溢出到 -2^31。

你需要在这里使用 BigIntegers,像这样:

Biginteger bx = new BigInteger(x);
BigInteger new BigInteger(50).multiply(bx.pow(3)).multiply(new BigInteger(-150))
    .multiply(bx.pow(2)).multiply(new BigInteger(400)).multiply(bx).divide(3);

【讨论】:

  • 所以不可能做这个数学?如何打印很长的结果?为什么 352 会溢出,而 500 不会溢出?
  • 我正在更新我的答案,请稍等。
  • @user2582318 你可以使用BigInteger。通过使用BigInteger 方法,而不是new BigInteger(String)
  • 对于 32 位有符号整数,它是 2^31-1 到 -2^31。
  • @LutzL 谢谢,我忘记了符号位。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-17
  • 1970-01-01
  • 1970-01-01
  • 2014-07-15
  • 1970-01-01
  • 2021-10-11
相关资源
最近更新 更多