来自 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/