【问题标题】:Error: Operator '!' cannot be applied to operand of type 'int'错误:运算符“!”不能应用于“int”类型的操作数
【发布时间】:2013-10-13 20:30:19
【问题描述】:

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

【问题讨论】:

  • 只需从这个 (!(x & (x - 1))) 到这个 ((x & (x - 1))) 中删除否定运算符,它就会起作用并为您提供所需的结果.

标签: c# operators boolean-logic


【解决方案1】:

在 C# 中,值 0 不等于 false,并且 different than 0 不等于 true,在 C++ 中就是这种情况。

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


操作x & (x - 1) 给出int(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) 也是有效的。

【讨论】:

  • 当我替换 '!'使用“-”它正在工作并将表达式更改为布尔类型。它奏效了。
  • 要反转序数的所有位,请使用~ 运算符。
  • @LasseV.Karlsen ~ 正在编译,但不适用于解决方案的逻辑
  • 但它们确实是平等的,但语言只是不接受这一点,因为它应该是抽象的。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-02
    • 2015-08-09
    • 2015-01-25
    • 2011-12-31
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多