错误:运算符“!” 不能应用于“int”类型的操作数

Aru*_*dey 3 c# boolean-logic operators

我是 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");
    }
Run Code Online (Sandbox Code Playgroud)

Pie*_*ult 5

在 C# 中,值0不等于falsedifferent than 0也不等于true,在 C++ 中就是这种情况。

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


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

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

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

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");
}
Run Code Online (Sandbox Code Playgroud)

我曾经== 0删除!, 但!((x & (x - 1)) != 0)也将是有效的。