3

我是 C 语言编程的新手,正在编写程序来确定一个数字是否是 2 的幂。但是作为运算符'!'出现错误 不能应用于 int 类型的操作数。认为相同的程序在 C++ 中运行良好。这是代码:

    public static void Main(String[] args)
    {
        int x;

        Console.WriteLine("Enter the number: ");

        x = Convert.ToInt32(Console.ReadLine());


        if((x != 0) && (!(x & (x - 1))))

            Console.WriteLine("The given number "+x+" is a power of 2");
    }
4

2 回答 2

5

In C#, the value 0 does not equal false, and different than 0 does not equal true, which is the case in C++.

For example, this expression is valid in C++ but not C# : while(1){}. You must use while(true).


The operation x & (x - 1) gives an int (int bitwise AND int) so it's not converted to boolean by default.

To convert it to a bool, you may add the == or != operator to your expression.

So your program can be converted to this :

public static void Main(String[] args)
{
    int x;

    Console.WriteLine("Enter the number: ");
    x = Convert.ToInt32(Console.ReadLine());

    if((x != 0) && ((x & (x - 1)) == 0))
        Console.WriteLine("The given number "+x+" is a power of 2");
}

I used == 0 to remove the !, but !((x & (x - 1)) != 0) would also be valid.

于 2013-10-13T20:35:08.847 回答
-1

我通过将布尔类型分配给表达式并替换“!”得到了答案 和 '-'

        public static void Main(String[] args)
        {
        int x;
        x = Convert.ToInt32(Console.ReadLine());
        bool y = ((x!=0) && -(x & (x-1))==0);
        if(y)
            Console.WriteLine("The given number is a power of 2");
        else
            Console.WriteLine("The given number is not a power of 2");
        Console.Read();
于 2013-10-13T21:13:17.803 回答