Python 教程之运算符(3)—— G-Fact 19(布尔逻辑和位非运算符)

Ichjns

关注

阅读 80

2022-09-18


包括 C、C++、Java 和 Python 在内的大多数语言都提供布尔类型,可以设置为FalseTrue。考虑以下在布尔值上 

使用逻辑非(或!)运算符的程序。

一个在布尔值上使用逻辑非或!的 C++ 程序

#include <iostream>
using namespace std;

int main(){
// 我们正在制作 false 和 true 的变量存储 bool 表达式,它也可以写成 (1) 代表“真”,(0) 代表“假”
bool is_it_true = false;
bool is_it_false = true;

// 下面的代码首先打印 false (0),然后打印 true (1),因为我们在第二种情况下使用了 'not' (!) 运算符
cout << is_it_true << endl;
cout << !is_it_true << endl;

// 下面的代码首先打印 true (1),然后打印 false (0),因为我们在第二种情况下使用了 'not' (!) 运算符
cout << is_it_false << endl;
cout << !is_it_false << endl;
return 0;
}

一个在布尔值上使用逻辑非或!的 Python 程序

a = not True
b = not False
print a
print b
# 输出: False
# True

一个在布尔值上使用逻辑非或! 的 C# 程序

using System;

class GFG
{
public static void Main
{
bool a = true, b = false;
Console.WriteLine(!a);
Console.WriteLine(!b);
}
}
// 输出: False
// True

一个在布尔值上使用逻辑非或!的 javascript 程序

<script>
var a = true, b = false;
document.write(!a+"<br/>");
document.write(!b);

// 输出: False
// True

输出

0
1
1
0

上述程序的输出符合预期,但如果我们之前没有使用过按位非(或~) 运算符,则程序后面的输出可能与预期不符。

一个在布尔值上使用按位非或 ~ 的 Python 程序

a = True
b = False
print ~a
print

在布尔值上使用按位非或 ~ 的 C/C++ 程序

#include <bits/stdc++.h>
using namespace std;
int main(){
bool a = true, b = false;
cout << ~a << endl << ~b;
return 0;
}

一个在布尔值上使用 Bitwise Not 或 ~ 的 Java 程序

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

结论: 
“逻辑非或!” 用于布尔值,“按位非或~”用于整数。当应用整数运算符时,C/C++ 和 python 等语言会自动将布尔值提升为整数类型,但是 Java 并没有这样做。

精彩评论(0)

0 0 举报