将 Biginteger 值乘以双精度值

问题描述 投票:0回答:3

我想像这样将一个 Biginteger 乘以一个 double

buyableObjects[index - 1].cost = buyableObjects[index - 1].cost * BigInteger.Pow((BigInteger)multiplier, buyableObjects[index - 1].indexMultiplier);

问题是 multiplier 是一个等于 1.15 的双精度值,而 BigInteger 忽略了 0.15。有没有办法将我的对象的成本(也是一个 Biginteger 值)乘以 double 值 1.15 并将其四舍五入为一个 biginteger?

c# unity3d double biginteger
3个回答
2
投票

您可以乘以 115,然后除以 100。


0
投票

我们可以看到 here BigInteger.Pow() 接受一个 BigInteger 后跟一个常规的 Base 32 整数。因此,如果您只想使用双精度数,我不明白您为什么要使用 BigInteger.Pow() 函数。

因为我们知道 multiplier 是一个 double 而 buyableObjects[index-1].indexMultiplier 是一个整数, 我会做

double finalMultiplier = Math.Pow(multiplier, buyableObjects[index-1].indexMultiplier);

然后你只需要面对将 BigInteger 乘以 double 的问题,你可以通过将其分解为乘法和除法来解决。

比如说 finalMultiplier = 2.27;此时您可能需要进行一些舍入,因为我们不确定 finalMultiplier 的小数位数。您可以使用 Math.Round() 函数实现此目的。 例如:

    int decimalPlaces = 2;
    double finalMultiplier = 2.225f;
    finalMultiplier = Math.Round(finalMultiplier,decimalPlaces, MidpointRounding.ToEven);
    //Will round 2.225 to 2.22
    BigInteger cost = new BigInteger(500);
    cost *= ((BigInteger) (finalMultiplier * Math.Pow(10, decimalPlaces))); //Multiply by 222
    cost /= (BigInteger) (Math.Pow(10,decimalPlaces)); //Divide by 100
    print(cost); //1110

这里有一些关于 C# 中不同舍入模式的信息。这样做将帮助您指定希望如何进行舍入,并且我已经向您展示了如何实现其他人所说的关于分解小数的一些内容。我会让你自由地替换正确的变量,但希望这会有所帮助!您所要做的就是用您的 BigInteger 替换成本并使用我在那里提供的 finalMultiplier。您可以根据需要自定义 decimalPlaces。


0
投票
我的贡献。它的工作原理是将数字放在那里,然后摇晃它们直到有东西弹出。它还将真实答案四舍五入到最接近的整数,不像其他一些 .NET 函数那样四舍五入到最接近的偶数,这是令人费解的。

public static class BigIntegerHelper { public static BigInteger MultiplyByDouble(this BigInteger x, double y) { BigInteger result = 0; double accumulatingRemainder = 0; for (var tensExp = 0; tensExp < 19; tensExp++) { var trimmed = (long)y; var unshifted = trimmed * x; var shifter = (long)Math.Pow(10, tensExp); accumulatingRemainder += (double)(unshifted % shifter) / shifter; result += unshifted / shifter; y = (y - trimmed) * 10; } return result + (long)(accumulatingRemainder + 0.5); } }

像这样使用它:

var answer = myBigIntegerVariable.MultiplyByDouble(myDoubleVariable);

© www.soinside.com 2019 - 2024. All rights reserved.