1

我的程序有什么问题?

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

}

我有错误

非静态字段、方法或属性需要对象引用。

4

4 回答 4

5

使方法isPowerOfTwo静态:

public static bool isPowerOfTwo (uint x)

方法Main是静态的,因此您只能在其中调用同一类的静态方法。然而isPowerOfTwo,就目前而言,它是一个实例方法,它只能在Program类的实例上调用。当然,您也可以Program在里面创建一个类的实例Main并调用它的方法,但这似乎是一种开销。

于 2013-07-02T06:20:04.153 回答
2

除了指出该方法应该是静态的之外,可能值得知道一种更有效的方法来确定一个数字是否是 2 的幂,使用位算术:

public static bool IsPowerOf2(uint x)
{
    return (x != 0) && (x & (x - 1)) == 0;
}
于 2013-07-02T06:29:08.757 回答
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);
    } 
}
于 2013-07-02T06:21:16.370 回答
1

你忘了静态...

public static bool isPowerOfTwo (uint x)
于 2013-07-02T06:23:15.837 回答