【问题标题】:BigInteger addition always 0BigInteger 加法总是 0
【发布时间】:2015-05-07 09:31:34
【问题描述】:

我有以下问题:尝试添加 BigIntegers 的总和时,结果仍然为 0。

代码如下:

 public void NumberOfOutcomes(int x, int y){
   BigInteger first = BigInteger.valueOf(0);
   BigInteger second = BigInteger.valueOf(0);
   for(int i = 0; i <= (x / 2); i++){
       first.add( fac(x - i).divide((fac(x - 2*i).multiply(fac(i)))) );
       System.out.println("First " + first.add( fac(x - i).divide((fac(x - 2*i).multiply(fac(i)))) ));
    }

   for(int i = 0; i <= (y / 2); i++){
       second.add( fac(y - i).divide((fac(y - 2*i).multiply(fac(i)))) );
       System.out.println("Second " + second.add( fac(y - i).divide((fac(y - 2*i).multiply(fac(i)))) ));
    } 
   System.out.println("First " + first);
   System.out.println("Second " + second);
   System.out.println(first.multiply(second));
   }

这里fac是阶乘函数。

这是终端上的内容:

points1.NumberOfOutcomes(2, 3)
前 1
前 1
第二个 1
第二个 2
前 0
第二个 0
0

【问题讨论】:

  • first.add(...) 不会改变 first
  • 我明白了,但我能做些什么呢?
  • 顺便说一句,你可以用BigInteger.ZERO代替BigInteger.valueOf(0)
  • first = first.add(...);

标签: java add biginteger factorial


【解决方案1】:

这是因为BigInteger不可变的,这意味着它的值不会改变。所以first.add(x) 将创建一个新的 BigInteger 包含计算结果,即只需将结果重新分配给第一个,如first = first.add(...)

【讨论】:

    【解决方案2】:

    BigInteger 类的add 方法返回操作数与已存储在对象本身中的值之和。但它不会将结果存储在对象中(第一个或第二个)。 它的工作方式与

    不同
    first += value;    
    

    实际上,你必须让它看起来像这样:

    first = first.add(value);    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2012-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多