错误:操作员'!'不能应用于'int'类型的操作数

时间:2013-10-13 20:30:19

标签: c# operators boolean-logic

我是C sharp编程的新手,正在编写程序以确定数字是否为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");
    }

2 个答案:

答案 0 :(得分:4)

在C#中,值0不等于false,而different than 0不等于true,这是C ++中的情况。

例如,此表达式在C ++中有效,但不是 C#:while(1){}。您必须使用while(true)


操作x & (x - 1)给出int(int按位AND int),因此默认情况下它不会转换为布尔值。

要将其转换为bool,您可以在表达式中添加==!=运算符。

所以你的程序可以转换成这个:

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

我使用== 0删除!,但!((x & (x - 1)) != 0)也有效。

答案 1 :(得分:0)

我通过为表达式指定布尔类型并替换'!'来得到答案用' - '

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