📜  G-Fact 19(布尔逻辑和位非运算符)

📅  最后修改于: 2022-05-13 01:54:31.713000             🧑  作者: Mango

G-Fact 19(布尔逻辑和位非运算符)

包括 C、C++、 Java和Python在内的大多数语言都提供布尔类型,可以设置为FalseTrue
考虑以下在布尔值上使用逻辑非(或!)运算符的程序。

C/C++

// A C/C++ program that uses Logical Not or ! on boolean
#include 
#include 

int main()
{
    bool a = 1, b = 0;
    a = !a;
    b = !b;
    printf("%d\n%d", a, b);
    return 0;
}
// Output: 0
//         1


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++

// 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);
    }
}

输出:

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