G-Fact 19(布尔逻辑和位非运算符)
包括 C、C++、 Java和Python在内的大多数语言都提供布尔类型,可以设置为False或True 。
考虑以下在布尔值上使用逻辑非(或!)运算符的程序。
// A C/C++ program that uses Logical Not or ! on boolean
#include
Java
// A Java program that uses Logical Not or ! on boolean
import java.io.*;
class GFG
{
public static void main (String[] args)
{
boolean a = true, b = false;
System.out.println(!a);
System.out.println(!b);
}
}
// Output: False
// True
Python
# A Python program that uses Logical Not or ! on boolean
a = not True
b = not False
print a
print b
# Output: False
# True
C#
// C# program that uses Logical
// Not or ! on boolean
using System;
class GFG
{
public static void Main ()
{
bool a = true, b = false;
Console.WriteLine(!a);
Console.WriteLine(!b);
}
}
// Output: False
// True
// This code is contributed
// by Rajput-Ji
Javascript
Python
# A Python program that uses Bitwise Not or ~ on boolean
a = True
b = False
print ~a
print ~b
C/C++// C/C++ program that uses Bitwise Not or ~ on boolean
#include
using namespace std;
int main()
{
bool a = true, b = false;
cout << ~a << endl << ~b;
return 0;
}
Java
// A Java program that uses Bitwise Not or ~ on boolean
import java.io.*;
class GFG
{
public static void main (String[] args)
{
boolean a = true, b = false;
System.out.println(~a);
System.out.println(~b);
}
}
上述程序的输出符合预期,但如果我们之前没有使用过按位非(或~)运算符,则程序后面的输出可能与预期不符。
Python
# A Python program that uses Bitwise Not or ~ on boolean
a = True
b = False
print ~a
print ~b
// C/C++ program that uses Bitwise Not or ~ on boolean
#include
Java
// A Java program that uses Bitwise Not or ~ on boolean
import java.io.*;
class GFG
{
public static void main (String[] args)
{
boolean a = true, b = false;
System.out.println(~a);
System.out.println(~b);
}
}
输出:
6: error: bad operand type boolean for unary operator '~'
System.out.println(~a);
^
7: error: bad operand type boolean for unary operator '~'
System.out.println(~b);
^
2 errors