逻辑运算符
逻辑运算符用来连接多个 bool 类型表达式,实现多个条件的复合判断。
C# 中的逻辑运算符包括:
- 逻辑非 (
!) - 逻辑与 (
&&) - 逻辑或 (
||)
逻辑非
逻辑非用来对某一个 bool 类型表达式 取反,即“真变假”或“假变真”。
csharp
Console.WriteLine(1 > 0); //条件表达式为 true,输出 True
Console.WriteLine(!(1 > 0)); //用逻辑非对条件表达式取反,输出 False逻辑与
逻辑与用来判断 2 个 bool 类型表达式是否同时为 true 。
csharp
int x = 5, y = 2; //同时声明 2 个 int 型变量并赋值
Console.WriteLine(x>3 && y>3); //判断 x>3 和 y>3 是否同时为 true,由于 y>3 为 false,所以整个表达式为 false- 只有当
&&两边的表达式均为 true 时,整个表达式才为 true; - 若任意一个表达式为 false,整个表达式即为 false。
逻辑或
逻辑或用来判断 2 个 bool 类型表达式中是否有一个为 true 。
csharp
int x = 5, y = 2; //同时声明 2 个 int 型变量并赋值
Console.WriteLine(x>3 || y>3); //判断 x>3 和 y>3 是否有一个为 true,由于 x>3 为 true,所以整个表达式为 true- 只要
||两边的表达式有一个为 true,整个表达式即为 true; - 若两边的表达式均为 false,整个表达式为 false。
总结
&&运算符,两边同真才算真,一边为假就算假;||运算符,一边为真即为真,两边同假才是假。
csharp
using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(true || false); //输出 True
Console.WriteLine(true && false); //输出 False
Console.WriteLine(!false); //输出 True
}
}
}csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
// 李英俊在公交车上坐的是爱心座,这个座位是提供给 6 岁以下儿童和 60 岁以上老人的。
int age = 4; //年龄
if (age < 6 || age > 60)
Console.WriteLine("请坐爱心座!");
else
Console.WriteLine("请坚持一下!");
}
}
}csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
// 小张想结婚,未来丈母娘开出的条件是:存款必须过 10 万,必须有房子,这两条少一条都不行。
double money = 200000.00; // 存款
bool hasHouse = true; // 是否有房
Console.Write((money > 100000 && hasHouse) ? "可以结婚" : "不可以结婚");
}
}
}csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
// 丽丽选择男朋友的标准,要么是“工程师”,要么是“运动员”,二者居其一即可
string job = "攻城师";
Console.Write((job == "工程师" || job == "运动员") ? "是理想的男友" : "不是理想的男友");
}
}
}