gpt4 book ai didi

java - BigInteger 数学函数不返回预期值

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:40:21 24 4
gpt4 key购买 nike

我有一个 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

有人可以帮忙解决这个问题吗?

最佳答案

替换这一行

bigInt32Bit.add(bI);

bigInt32Bit = bigInt32Bit.add(bI);

你这样做是因为 BigIntegerimmutable .这意味着您必须为 bigInt32Bit 创建一个新值,而不是仅仅调整一个旧值。另外(如 @justhalf 所说)替换行

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

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

以便您在应用数学运算符时使用正确的值。

关于java - BigInteger 数学函数不返回预期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34437024/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com