簡體   English   中英

在C#中檢查整數是否為2的冪

[英]Check if an Integer Is a Power Of Two in 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);
    } 
}

}

我有錯誤

非靜態字段,方法或屬性需要對象引用。

Make方法isPowerOfTwo靜態:

public static bool isPowerOfTwo (uint x)

方法Main是靜態的,因此只能在其中調用同一類的靜態方法。 但是,當前的isPowerOfTwo是實例方法,只能在Program類的實例上調用它。 當然,您也可以在Main內部創建一個Program類的實例並調用它的方法,但這似乎是一個開銷。

除了指出該方法應該是靜態的以外,可能還需要了解一種使用位算術確定數字是否為2的冪的更有效的方法:

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

您有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);
    } 
}

你忘了靜態...

public static bool isPowerOfTwo (uint x)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM