我尝试使用以下代码显示数字的二进制等效,但我收到错误,我没有得到错误背后的原因:
using System;
class NumToBin{
static void main(){
int num=7;
for(int i=0;i<=32;i++){
if(num &(1<<i)==1)// getting an error on this line
Console.WriteLine("1");
else
Console.WriteLine("0");
}
Console.ReadKey(true);
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码我得到以下错误,我不知道这个错误背后的原因?
Operator '&' cannot be applied to operands of type 'int' and 'bool' (CS0019)
错误是操作员优先顺序的结果,要修复它你只需要添加括号,更改:
if(num &(1<<i)==1)
Run Code Online (Sandbox Code Playgroud)
至
if((num & (1<<i)) == 1)
Run Code Online (Sandbox Code Playgroud)