逻辑运算符

对bool类型进行逻辑运算

逻辑与

符号:&& 并且
规则:对两个bool值进行逻辑运算,有假则假,同真为真。

bool result = true && false;
Console.WriteLine(result);
result = true && true;
Console.WriteLine(result);
result = false && true;
Console.WriteLine(result);

bool相关的类型bool变量,条件运算符。
逻辑运算符优先级低于条件运算符,算术运算符。

int i = 3;
//1 < i < 5;
//true && true
result = i > 1 && i < 5;
Console.WriteLine(result);

多个逻辑与组合使用:

int i2 = 5;
//true && false && true && true
//在没有括号的情况下,从左到右,依次看即可
//有括号,先看括号内
result = i2 > 1 && i2 < 5 && i > 1 && i < 5;
Console.WriteLine(result);

逻辑或

符号:|| 或者
规则:对两个bool值进行逻辑运算,有真则真,同假为假。

result = true || false;
Console.WriteLine(result);
result = true || true;
Console.WriteLine(result);
result = false || true;
Console.WriteLine(result);
result = false || false;
Console.WriteLine(result);

//false || true
result = 3 > 10 || 3 < 5;
Console.WriteLine(result);

int a = 5;
int b = 11;
//true || true || false
result = a > 1 || b < 20 || a > 5;
Console.WriteLine(result);

小结:
? && ?
? || ?
? 可以是写死的bool变量或者bool值
还可以是调节运算符相关

逻辑非

符号:!
规则:对一个bool值进行取反,真变假,假变真。

result = !false;
Console.WriteLine(result);
result = !true;
Console.WriteLine(result);

result = !!true;
Console.WriteLine(result);

逻辑非的优先级较高

result = !(3 > 2);
Console.WriteLine(result);

a = 5;
result = !(a > 5);
Console.WriteLine(result);

混合使用优先级问题

规则:!(逻辑非)优先级最高,&&(逻辑与)优先级高于||(逻辑或)
逻辑运算符优先级低于算数运算符,条件运算符(逻辑非除外)

bool gameOver = false;
int hp = 100;
bool isDead = false;
bool isMustOver = true;

//false || false && true || true;
//false || false || true
result=gameOver || hp < 0 && !isDead || isMustOver;
Console.WriteLine(result);

逻辑运算符短路规则

|| 有真则真
只要逻辑与或者逻辑或,左边满足了条件,对于我们来说,已经不重要。

int i3 = 1;
//i3 > 0 true
//逻辑或,有真则真,那左边只要为真了,右边就不重要
result = i3 > 0 || ++i3 >= 1;
Console.WriteLine(i3);
Console.WriteLine(result);
//false && i3 ++ > 1;抛去后面不去计算

//逻辑与,有假则假,那左边只要为假了,右边就不重要
result = i3 < 0 && ++i3 >= 1;
Console.WriteLine(i3);
Console.WriteLine(result);
  • 14
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不背完3500个考研英语词汇不改名

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值