gpt4 book ai didi

c# - 在 C# 中计算 2 的整数幂的简单方法?

转载 作者:可可西里 更新时间:2023-11-01 08:16:33 26 4
gpt4 key购买 nike

我确信这并不像我想象的那么难。

想使用与 Math.Pow(double, double) 等价的东西,但输出一个整数。我担心 float 的舍入错误。

我能想到的最好的是:

uint myPower = 12;
uint myPowerOfTwo = (uint)Math.Pow(2.0, (double)myPower);

我想到了这个:

uint myPowerOfTwo = 1 << myPower;    // doesn't work

但我收到错误消息,即运算符“<<”不能与类型为 int or 和 uint 的操作数一起使用。

有什么建议吗?一如既往的感谢。

最佳答案

您必须为移位运算符的第二个操作数(右侧)使用带符号的整数:

int myPower = 12;
int myPowerOfTwo = 1 << myPower;

当然您可以将结果转换为其他数字类型,例如 uint:

uint myPowerOfTwo = (uint) (1 << myPower);   

来自 MSDN :

The left-shift operator (<<) shifts its first operand left by the number of bits specified by its second operand. The type of the second operand must be an int.

关于c# - 在 C# 中计算 2 的整数幂的简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5507103/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com