2的n次方 [英] 2 to the power of n

查看:137
本文介绍了2的n次方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



谁能向我展示如何在C#中编写以n的幂为单位的计算2的代码?

Hi,

Can anyone show me how I can write code for computing 2 to the power of n in C#?

推荐答案

我认为预期的答案是特定于2的幂的整数方法:

I think intended answer is integer method specific to powers of 2:

static int PowerOfTwo(int power) {
   return 1 << power;
}


使用Math.Pow.

http://msdn.microsoft.com/en-us/library/system.math. pow.aspx [ ^ ]
Use Math.Pow.

http://msdn.microsoft.com/en-us/library/system.math.pow.aspx[^]


如果n是+ | N的元素,则可以这样操作:
If n is element of +|N you can do it like this:
public static double twoPow(int n)
{
    if(n==0)
        return 1.0;
    else
        return 2.0 * twoPow(n-1);
}



当然,这是非常严格的,纯粹是为了给您提供一个想法,您始终可以按照Nishant告诉您的内容进行操作.

干杯!



This is of course very restrictive and purely to give you an idea and you can always go by what Nishant told you.

Cheers!


这篇关于2的n次方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆