大整数运算函数未返回预期值

3

我有一个BigInteger方法,它接受一个由4个数字组成的string[]数组输入,将这些数字转换为int[],然后对其应用多种数学运算。

public BigInteger convert32Bit(String[] array)
{
    System.out.println("Array being converted is "+Arrays.toString(array)+"\n");
    int[] tempArray = new int[array.length];
    ArrayList<BigInteger> tempBigIntList = new ArrayList<BigInteger>();
    int i = 0;
    for(String s:array)
    {
        int power = 4-i;
        tempArray[i]= Integer.parseInt(s);
        String string = Integer.toString(tempArray[0]);
        BigInteger myBigInt = new BigInteger(string);
        BigInteger num2 = myBigInt.multiply(new BigInteger("256").pow(power));
        System.out.println(tempArray[i]+" is being multiplied by 256^"+power+" which equals "+num2);
        tempBigIntList.add(num2);
        i++;
    }

    BigInteger bigInt32Bit = new BigInteger("0");
    for(BigInteger bI:tempBigIntList)
    {
        bigInt32Bit.add(bI);
    }

    System.out.println("\nThe final value is "+bigInt32Bit);

    return bigInt32Bit;
}

然而,存在一个问题。如果我将数组"123", "0", "245", "23"作为输入,则会得到以下输出。

Wrong output

我期望的输出是:
Array being converted is [123, 0, 245, 23]

123 is being multiplied by 256^4 which equals 528280977408
0 is being multiplied by 256^3 which equals 0
245 is being multiplied by 256^2 which equals 16056320
23 is being multiplied by 256^1 which equals 5888

The final value is 528297039616

能有人帮忙修复这个问题吗?


1
在你的循环中,String string = Integer.toString(tempArray[0]); 应该改为 tempArray[i] - justhalf
@justhalf 谢谢。这解决了计算数值的问题。 - Dan
为什么会有关闭投票? - Dan
1
如果这只是一个打字错误,那么这个问题应该被关闭,因为它可能不会帮助未来的读者。但由于您对BigInteger的不可变性存在困惑,我认为这个问题是相当好的。 - justhalf
1
@Dan,因为这个问题对于其他访问者来说可能没有帮助。你不必担心,因为你的问题已经得到解决了。 - Tagir Valeev
显示剩余2条评论
2个回答

3

请替换此行

bigInt32Bit.add(bI);

使用

bigInt32Bit = bigInt32Bit.add(bI);

您这样做是因为BigInteger不可变的。这意味着您必须为bigInt32Bit创建一个新值,而不是仅调整旧值。此外(如@justhalf所说),请替换该行。
String string = Integer.toString(tempArray[0]);

使用

String string = Integer.toString(tempArray[i]);

这样你就可以在应用数学运算符时使用正确的值。


1
他的代码中还有一个错别字,String string = Integer.toString(tempArray[0]); 应该是 tempArray[i] 而不是 tempArray[0] - justhalf
谢谢你们俩,问题已经解决了 :) - Dan
1
@TagirValeev:实际上你不需要将它更改为社区维基,这只是一个小错误 =) - justhalf

0

BigInteger是不可变的,因此bigInt32Bit.add(bI);将导致值为第一个元素的值。为了添加所有的值,你可以这样做:

 bigInt32Bit = bigInt32Bit.add(bI);//assign it

同时,您只是将数组的第一个元素作为bigInteger的输入传递,例如String string = Integer.toString(tempArray[0]);,应该是String string = Integer.toString(tempArray[i]);。如果数组没有在其他地方使用,我不会使用它,而是直接使用整数变量。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接