蓝鸥Unity开发基础——关系运算和逻辑运算学习笔记
本节内容 关系运算符 逻辑运算符
一、关系运算符
> >= < <= == !=
主要用于比较运算,比较的结果只有true或false两种情况,结果用boo类型变量存储
注意:判断是否相等,用==(双等号)
不能用零或非零代表bool值
代码演示:
using System;
namespace Lesson10
{
class MainClass
{
public static void Main (string[] args)
{
/*关系运算符*/
int a = 4;
int b = 9;
//关系运算符包括:>(大于) <(小于)>=(大于等于) <= (小于等于)==(等于,完全相等) !=(不等于)
bool r =a>b;
Console.WriteLine (r);
r = 5 == 5; // r=true;
r = 4 != 4; // r=true;
//关系运算符高于赋值预算法,低于一般的算术运算符
Console.WriteLine (r);
//为了避免记错运算级别,可以通过口号来解决问题
//r = (5 == 5);
//r = (4 != 4);
}
}
}
二、逻辑运算符
逻辑运算符在数学中也存在或且非,那么具体的C#中逻辑运算符怎么用?
1、逻辑或运算符——||
using System;
namespace Lesson10
{
class MainClass
{
public static void Main (string[] args)
{
/*关系运算符*/
int a = 4;
int b = 9;
//关系运算符包括:>(大于) <(小于)>=(大于等于) <= (小于等于)==(等于,完全相等) !=(不等于)
bool r =a>b;
Console.WriteLine (r);
r = 5 == 5; // r=true;
r = 4 != 4; // r=true;
//关系运算符高于赋值预算法,低于一般的算术运算符
Console.WriteLine (r);
//为了避免记错运算级别,可以通过口号来解决问题
//r = (5 == 5);
//r = (4 != 4);
//l逻辑运算符
//逻辑运算符—— ||
r =true || false;//两个操作数中,只要有一个是true,那么整个式子的结果就是true,否则就是fals
Console.WriteLine (r);
}
}
}
或运算符可以连接两个表达式,只要表达式是bool类型的值就可以
举例:
r =( (5 > 7) || (4 < 9)); // (5 > 7) false ,(4 < 9) true ,使用括号括起来避免运算符优先级问题(5 > 7) || (4 < 9)
Console.WriteLine (r);
2、逻辑与运算符——&&(and符号)
using System;
namespace Lesson10
{
class MainClass
{
public static void Main (string[] args)
{
/*关系运算符*/
int a = 4;
int b = 9;
//关系运算符包括:>(大于) <(小于)>=(大于等于) <= (小于等于)==(等于,完全相等) !=(不等于)
bool r =a>b;
Console.WriteLine (r);
r = 5 == 5; // r=true;
r = 4 != 4; // r=true;
//关系运算符高于赋值预算法,低于一般的算术运算符
Console.WriteLine (r);
//为了避免记错运算级别,可以通过口号来解决问题
//r = (5 == 5);
//r = (4 != 4);
//l逻辑运算符
//逻辑或运算符—— ||
//r =true || false;//两个操作数中,只要有一个是true,那么整个式子的结果就是true,否则就是fals
r =( (5 > 7) || (4 < 9));// (5 > 7) false ,(4 < 9) true ,使用括号括起来避免运算符优先级问题(5 > 7) || (4 < 9)
Console.WriteLine (r);
//逻辑与运算符—— &&
//两个操作数中,只要有一个是false,那么整个式子的结果就是false,否则为true
//r=(true &&true);//r=true
r = (4 > 7) && (4 * 2 <= 6);//r=false
Console.WriteLine (r);
}
}
}
与运算符的短路现象: 例如:r = (4 > 7) && (4 * 2 <= 6);计算机在计算4> 7的的结果中,得到了false,接下来计算机就不在进行运算,直接输出r=false,计算机不会再计算4 * 2 <= 6了。
举例:与运算符的短路+或运算符的短路
int x = 4;
r = (false && x++ < 10);
Console.WriteLine (r);
Console.WriteLine (x);
int y = 4;
r = (true || y++ < 10);
Console.WriteLine (r);
Console.WriteLine (y);
——监测到无法访问的表达式
3、逻辑与运算符——!(单目运算符)
逻辑非运算符——! 单目运算符
r=!true;//将它所连接的操作数取反
Console.WriteLine (r);