我的应用程序必须处理计算大数。如何将两个int相乘并获得BigInteger乘积而不溢出?具体来说,我必须获得"BaseCost" x ("multiplier" by the power of "level")
我测试了“ new BigInteger(100000000000000000000000)
”不起作用。因此,我认为“ if(BigInteger > (BigInteger)(Int1 * float1))
”不起作用。它可能会在“ (Int1 * float1)
”部分溢出。
答案 0 :(得分:0)
这就是我解决此问题的方法。我从GitHub的JcBernack使用了BigDecimal,这是下面的代码。
private BigInteger Example
{
get
{
return (BigInteger)(new BigDecimal(Int1) * Float2);
}
}
我使用了BigDecimal类,因为我无法将BigInteger与浮点数相乘。另外,在使用该类之前,我确保添加了一个BigInteger脚轮(来自uhDreamer的评论)。
public static explicit operator BigInteger(BigDecimal value)
{
BigDecimal floored = value.Floor();
return floored.Mantissa * BigInteger.Pow(10, floored.Exponent);
}
还有一个Int构造函数。
public BigDecimal(int t)
{
Exponent = 0;
Mantissa = t;
Normalize();
if(AlwaysTruncate)
{
Truncate();
}
}
现在,对于只需要乘以整数的开发人员,他们可以执行Int1(BigInteger) * Int2
。
当然,不要忘记System.Numerics命名空间。
答案 1 :(得分:-2)