2013-07-02 39 views
1

我的程序有什么问题?检查整数是否是C中的两个幂#

namespace ConsoleApplication1 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     bool check = isPowerOfTwo(255); 
     Console.WriteLine(check); 
     Console.ReadKey(); 
    } 

    public bool isPowerOfTwo (uint x) 
    { 
     while (((x % 2) == 0) && x > 1) 
     { 
      x /= 2; 
     } 
     return (x == 1); 
    } 
} 

}

我得到错误

一个对象引用是所必需的非静态字段,方法或属性。

+3

可能值得注意的是算法本身可以改进。你应该可以使用:'return x!= 0 &&((x-1)&x)== 0' – Iridium

回答

5

制作方法isPowerOfTwo静:

public static bool isPowerOfTwo (uint x) 

方法Main是静态的,所以你只能叫内就同一类的静态方法。然而,isPowerOfTwo,因为它目前代表的是一种实例方法,所以它只能在Program类的实例上调用。当然,您也可以在Main内创建一个Program类的实例并调用它的方法,但这似乎是一个开销。

+0

或者把它放在它自己的类中,实例化它并调用。 –

+2

..或者这样调用它:'Program program = new Program(); book check = program.isPowerOfTwo(255);'= D – Sinatr

+0

@Andrei,非常感谢。请你能解释一下为什么我需要静态方法吗? – Heidel

1

你有2个选项;

让你的isPowerOfTwo方法static喜欢;

public static bool isPowerOfTwo(uint x) 
{ 
    while (((x % 2) == 0) && x > 1) 
    { 
     x /= 2; 
    } 
    return (x == 1); 
} 

或者创建你的类的实例,然后调用你的方法;

class Program 
{ 
    static void Main(string[] args) 
    { 
     Program p = new Program(); 
     bool check = p.isPowerOfTwo(255); 
     Console.WriteLine(check); 
     Console.ReadKey(); 
    } 

    public bool isPowerOfTwo(uint x) 
    { 
     while (((x % 2) == 0) && x > 1) 
     { 
      x /= 2; 
     } 
     return (x == 1); 
    } 
} 
1

你忘了静态...

public static bool isPowerOfTwo (uint x) 
2

除了指出该方法应该是静态的,它可能是值得了解的一个更有效的方式使用位算术来确定数是否是2的幂:

public static bool IsPowerOf2(uint x) 
{ 
    return (x != 0) && (x & (x - 1)) == 0; 
}