在C#中计算2的整数幂的简单方法?
我确信这并不像我想象的那么困难。
想要使用等价于 Math.Pow(double, double) 但输出整数的东西。我担心浮点的舍入误差。
我能想到的最好的办法是:
uint myPower = 12;
uint myPowerOfTwo = (uint)Math.Pow(2.0, (double)myPower);
我想到了这一点:
uint myPowerOfTwo = 1 << myPower; // doesn't work
但我得到了运算符“<<”的错误不能与 int 或 和 uint 类型的操作数一起使用。
有什么建议吗?一如既往地感谢。
I'm sure this isn't as difficult as I'm making it out to be.
Would like to use something equivalent to Math.Pow(double, double)
but outputting an integer. I'm concerned about roundoff errors with the floating points.
The best I can come up with is:
uint myPower = 12;
uint myPowerOfTwo = (uint)Math.Pow(2.0, (double)myPower);
I thought of this:
uint myPowerOfTwo = 1 << myPower; // doesn't work
but I get the error that operator "<<" cannot be used with operands of type int or and uint.
Any suggestions? Thanks as always.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须对移位运算符的第二个操作数(右侧)使用有符号整数:
当然,您可以将结果转换为其他数字类型,例如 uint:
来自 MSDN:
you will have to use a signed integer for the second operand (right hand side) of the shift operator:
Of course you can cast the result to another numeric type such as uint:
From MSDN:
如果您创建扩展/静态方法,那么稍后会更容易找到并纠正任何错误,并且优化器仍会内联它:
然后您可以使用如下内容:
If you make an extension/static method, then it would be easier to find and correct any errors later and the optimizer would still inline it:
Then you can use like: