c# - Math.Pow 取整数值

标签 c# floating-accuracy pow

来自 http://msdn.microsoft.com/en-us/library/system.math.pow.aspx

int value = 2;
for (int power = 0; power <= 32; power++)
    Console.WriteLine("{0}^{1} = {2:N0}",
                      value, power, (long) Math.Pow(value, power));

Math.Pow 接受 double 作为参数,但在这里我们传递的是整数。

问题:如果隐式转换为 double 发生,是否存在浮点舍入错误的危险?

如果是,最好使用类似的东西:

public static int IntPow(int x, uint pow)
{
    int ret = 1;
    while (pow != 0)
    {
        if ((pow & 1) == 1)
            ret *= x;
        x *= x;
        pow >>= 1;
    }
    return ret;
}

最佳答案

在您的特殊情况下,当您计算 2 的 x 次方时,您可以使用简单的左移。这会将您的代码简化为:

public static int TwoPowX(int power)
{
    return (1<<power);
}

关于c# - Math.Pow 取整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11196700/

相关文章:

c# - 删除应用程序的 DLL 依赖项

c - IEEE 754 : How exactly does it work?

c++ - std::pow() 输出是……特别的?

c# - Caliburn NotifyOfPropertyChanged : System. InvalidCastException

c# - 具有多个参数的函数的 Resharper 右括号缩进

c++ - sprintf(buf, "%.20g", x)//buf应该多大?

java - Java有指数运算符吗?

java - Math.pow(9, 18) 和 9^18 有什么区别

c# - Entity Framework 6 中的基类?

c - C 中的整数除法将值向下舍入/结果为零