2013-07-02 41 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; 
}