是否有任何内置的 .NET 替代方案可以无误地使用数字的幂 (Math.Pow)?

Are there any built-in .NET alternatives for using power of a number (Math.Pow) without errors?

Math.Pow 似乎无法正常工作以获得较大的结果。可能是因为它使用 double 进行计算 (How is Math.Pow() implemented in .NET Framework?).

例如:

public static void Main()
{
    Console.WriteLine((long)Math.Pow(17, 13));
    Console.WriteLine(Pow(17, 13));
}

public static long Pow(int num, int pow)
{
    long answer = 1;
    for (int i = 0; i < pow; i++)
    {
        answer *= num;
    }

    return answer;
}

以上代码的结果是:

9904578032905936
9904578032905937

是否有任何内置的 .NET 替代方法可以无误地使用数字的幂?

BigInteger structure has a Pow 方法。此结构位于 System.Numerics 命名空间中,并在 .NET Framework 4.0 中引入。在使用它之前,您需要添加对 System.Numerics 程序集的引用。

using System;
using System.Numerics;

public static class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine(BigInteger.Pow(17, 13));   // 9904578032905937
    }
}

注意BigInteger只适用于整数运算;它不能处理小数。