运算符(C#)
算数运算符
+ - * / %
c#
//算数运算符
// + - * / %
//这跟我们初中的运算符一样
// + 加号
Console.WriteLine(1+2);//3
int a = 5 + 6;
Console.WriteLine(a);//11
// - 减号
Console.WriteLine(6-3);//3
int b = 10 - 6;
Console.WriteLine(b);//4
// * 乘号
Console.WriteLine(5*6);//30
int c = 6 * 6;
Console.WriteLine(c);//36
// / 除号
Console.WriteLine(6/6);//1
int e = 10 / 2;
Console.WriteLine(e);//5
// % 取余
//取余是一种数学运算符,表示一个数除以另一个数后所得到的余数.它在数学和计算机科学中被广泛使用. 在进行取余运算时,我们使用符号"%"表示.
Console.WriteLine(5%5);//0
int f = 4 % 3;
Console.WriteLine(f);//1
// * 1.整数和整数运算符,一定得到整数
// * 2.整数和小数运算,也可以得到小数
// * 3.整数不能除以0,也不能对0取余
// * 4.小数可以除以0,得到无穷大,对0取余得到NaN
注意: 0不能作为除数
赋值运算
c#
//= 相当于赋值运算
int aa = 10;
aa += 5;
aa = aa + 5;
Console.WriteLine(aa);//15
// ++的含义
// a++ ===> 在自身原来的基础上+1
int aaa = 10;
int bbb = aaa++;
Console.WriteLine(aaa);//11
Console.WriteLine(bbb);//10
// ++在前 先运算后赋值 ++在后先赋值后运算
int ccc = 11;
int ddd = ccc++;
int eee=++ccc;
int fff = --ccc;
Console.WriteLine(ddd);//11
Console.WriteLine(eee);//13
Console.WriteLine(fff);//12
比较运算符
c#
//比较运算符
// > 大于
// < 小于
// == 等于
// != 不等于
// >= 大于等于
// <= 小于等于
int a1 = 3;
int b1 = 5;
bool c1 = a1 > b1;
c1 = a1 != b1; // a1!=b1; 是正确的 所以c1就是TRUE
Console.WriteLine(c1);
逻辑运算符
c#
//逻辑运算符
// &(与), |(或) , ||(短路或) &&(短路与), !(非)
//&(逻辑运算符) 表示 和 与 and 两边都位true 结果都为true 只要有一边位false,结果就为false
Console.WriteLine(true&true); //true
Console.WriteLine(false&false); //false
Console.WriteLine(true&false); //false
Console.WriteLine(1<2&10<11); //true
// | (逻辑或运算) 表示 或 or 两边只要有一个true 结果就为true
Console.WriteLine(true | true); //true
Console.WriteLine(false | false); //false
Console.WriteLine(true |false); //true
Console.WriteLine(1 < 2 | 10 > 11);//true
// &&(短路与)
Console.WriteLine(true &&true); //true
Console.WriteLine(false && false); //false
Console.WriteLine(true && false); //false
Console.WriteLine(1 < 2 && 10 < 11); //true
//(短路或)
Console.WriteLine(true || true); //true
Console.WriteLine(false || false); //false
Console.WriteLine(true || false); //true
Console.WriteLine(1 < 2 || 10 > 11);//true
// && 和 & || 和| 的区别?
// 使用&& ||的时候,如果前面已经得到结果了,后面就不会执行了
// &和| 不管前面怎么样会执行完毕所有的运算
int sum1 = 6; int sum2 = 7;
bool vv = sum1 < sum2 || sum1++ == 6;
Console.WriteLine(vv);//true
Console.WriteLine(sum1);//6
//总结:
// & 遇到一个false 最终结果就为false
// | 遇到一个true 最终结果就为true
// && 遇到一个false 就直接结束运算,后续的代码不再执行(遇假则假)
// || 遇到一个true 就直接结束运算,后续的代码不在执行(遇真则真)
取反 ! 非
c#
// ! 非 取反 not true取反为FALSE FALSE取反为TRUE
Console.WriteLine(!(10>50));//TRUE
Console.WriteLine(!false);//true