BigInteger addition always 0

旧时模样 提交于 2019-12-08 19:46:35

问题


I have the following issue: when trying to add to a sum of BigIntegers the outcome remains 0.

Here is the code:

 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));
   }

Here fac is the factorial function.

Here is what comes on the terminal:

points1.NumberOfOutcomes(2, 3)
First 1
First 1
Second 1
Second 2
First 0
Second 0
0


回答1:


This is because BigInteger is immutable which means that its value does not change. So first.add(x) will create a new BigInteger containing the computations result, i.e. just reassign the result to first, like first = first.add(...).




回答2:


The add method of BigInteger class returns the sum of the operand and the value already stored in the the object itself. But it does not store the result in the object (first or second). It doesn't work in the same way as

first += value;    

actually, you have to make it look like this:

first = first.add(value);    


来源:https://stackoverflow.com/questions/30097093/biginteger-addition-always-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!