对于int和float的乘积如何对Int32 / 64的限制进行计算?

问题描述 投票:-1回答:1

我的应用程序必须处理计算大数。如何将一个int和一个float进行乘积并得到一个BigInteger乘积而不会溢出?具体来说,我必须获得"BaseCost" x ("multiplier" by the power of "level")

我测试了“ new BigInteger(100000000000000000000000)”不起作用。因此,我认为“ if(BigInteger > (BigInteger)(Int1 * float1))”无效。它可能会在“ (Int1 * float1)”部分中溢出。

c# biginteger
1个回答
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命名空间。

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