.NET 中的内置 Math.Pow() 函数将 double 基数提升为 double 指数并返回一个 double 结果.
The built-in Math.Pow() function in .NET raises a double base to a double exponent and returns a double result.
对整数执行相同操作的最佳方法是什么?
What's the best way to do the same with integers?
补充:似乎可以将 Math.Pow() 结果转换为 (int),但这会始终产生正确的数字并且没有舍入错误吗?
Added: It seems that one can just cast Math.Pow() result to (int), but will this always produce the correct number and no rounding errors?
推荐答案一个相当快的方案可能是这样的:
A pretty fast one might be something like this:
int IntPow(int x, uint pow) { int ret = 1; while ( pow != 0 ) { if ( (pow & 1) == 1 ) ret *= x; x *= x; pow >>= 1; } return ret; }请注意,这不允许负权力.我将把它留给你作为练习.:)
Note that this does not allow negative powers. I'll leave that as an exercise to you. :)
添加:哦,是的,差点忘了 - 还要添加上溢/下溢检查,否则您可能会遇到一些令人讨厌的惊喜.
Added: Oh yes, almost forgot - also add overflow/underflow checking, or you might be in for a few nasty surprises down the road.
更多推荐
你如何在 C# 中做*整数* 取幂?
发布评论