[英]Error: Operator '!' cannot be applied to operand of type 'int'
I am newbie to C sharp programming and was writing the program to determine whether a number is power of 2 or not. 我是C sharp编程的新手,正在编写程序以确定数字是否为2的幂。 But getting error as Operator '!'
但是像操作员那样得到错误!' cannot be applied to operand of type int.
不能应用于int类型的操作数。 Thought the same program works well in C++.
认为同样的程序在C ++中运行良好。 Here is the code:
这是代码:
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");
}
In C#, the value 0
does not equal false
, and different than 0
does not equal true
, which is the case in C++. 在C#中,值
0
不等于false
, different than 0
不等于true
,这在C ++中就是这种情况。
For example, this expression is valid in C++ but not C# : while(1){}
. 例如,此表达式在C ++中有效,但在 C#:
while(1){}
无效。 You must use while(true)
. 你必须使用
while(true)
。
The operation x & (x - 1)
gives an int
(int bitwise AND int) so it's not converted to boolean by default. 操作
x & (x - 1)
给出一个int
(int按位AND int),因此默认情况下它不会转换为boolean。
To convert it to a bool
, you may add the ==
or !=
operator to your expression. 要将其转换为
bool
,可以在表达式中添加==
或!=
运算符。
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 !
我用
== 0
删除了!
, but !((x & (x - 1)) != 0)
would also be valid. ,但是
!((x & (x - 1)) != 0)
也是有效的。
I got the answer by assigning boolean type to the expression and replace '!' 我通过为表达式指定布尔类型并替换'!'来得到答案 with '-'
用' - '
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.