1,邏輯運算符:
&& 邏輯與,可以理解為並且的意思.
|| 邏輯或,可以理解為或者的意思,也就是條件可以2取一
! 邏輯非 (一元表達式)
2,邏輯與運算:&&
邏輯與連接的2個表達式,要能夠求解成bool類型,一般情況下都是關系表達式.
整個邏輯與運算結果也是bool類型
bool isRight=表達式1&&表達式2 :當表達式1、2全為true時,其表達式的結果為true.
| 表達式1 | 表達式2 | 邏輯與結果 |
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
綜上所述,只有當2個表達式全為True時,其結果才能為True.
例題:
int age=20,wight=120;
bool result=age>=18&&wight>=100;
Console.WriteLine("結果={0}",result);
Console.ReadKey();
輸出結果:Ture.
3,邏輯或運算:||
邏輯或連接的2個表達式,要能夠求解成bool類型,一般情況下都是關系表達式.
整個邏輯或運算結果也是bool類型
bool isRight=表達式1||表達式2:當表達式1、2中有一個為true ,其表達式的結果為true.
| 表達式1 | 表達式2 | 邏輯或結果 |
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
綜上所述,只要有1個表達式為True時,其結果都為True.
例:
try
{
Console.WriteLine("請輸入你的身高"); //假設輸入值為130
int height=Convert.ToInt32(Console.ReadLine());
Console.WriteLine("請輸入你的體重");
int weight=Convert.ToInt32(Console.ReadLine());
bool result=height>=120||weight>=50;
Console.WriteLine("{0}",result);
}
catch
{
Console.WriteLine("你輸入有誤,請重新輸入");
}
Console.ReadKey();
輸出結果為:True
4,邏輯非運算(取反):!(這是一個一元運算符)
用法:
!(布爾類型的表達式)
作用:
如果布爾類型的表達式為True,加!后其整個式子的結果為False.
如果布爾類型的表達式為False,加!后其整個式子的結果為True.
bool isRight=!表達式:如果表達式的結果為true,則取反后為false,反之為true.
例:
try
{
Console.WriteLine("請輸入你的身高"); //假設輸入值為130
int height=Convert.ToInt32(Console.ReadLine());
Console.WriteLine("請輸入你的體重");
int weight=Convert.ToInt32(Console.ReadLine());
bool result=height>=120||weight>=50;
Console.WriteLine("{0}",!result);
}
catch
{
Console.WriteLine("你輸入有誤,請重新輸入");
}
Console.ReadKey();
輸出結果為:False
