04.运算符与表达式(上)

1.= 号

=号表示赋值的意思,表示把等号右边的值赋值给等号左边的变量。

int a = 10;//等号右侧的10赋值给了变量a

2.+号

在c#中+号有两个作用:

1.连接 当+号两边有一个是字符串的时候,此时+号起到连接的作用

//相连
string name = "element";
int age = 20;
Console.WriteLine(name + age);//out  element20

2.相加 当+号两边都是数字的时候,+号起到相加的作用

//相加
Console.WriteLine(5+5);//out 10

2.算数运算符

1.+ - * /

加减乘除。四则运算。

运算优先级:先乘除,后加减。有括号先算括号内的,相同优先级别则从左到右按顺序计算。

//相加
Console.WriteLine(5+5);//out 10
//相减
Console.WriteLine(5-5);//out 0
//相乘
Console.WriteLine(5*5);//out 25
//相除  两个整数相除 舍弃余数
Console.WriteLine(5/5);//out 1
//取余
Console.WriteLine(5%5);//out 0

演示:求三科总成绩和平均成绩

int china = 80;//先声明三个变量 用来分别存储我们三个科目的分数
int english = 20;
int math = 30;
Console.WriteLine(china + english + math);//总成绩  out 130
Console.WriteLine((china + english + math)/3);//平均成绩 out 43

演示求个位 十位 百位的数值

int day = 365;
int baiwei = day / 100;
int shiwei = (day %100) / 10;
int gewei = (day % 100)%10;

Console.WriteLine($"百位{baiwei}十位{shiwei}个位{gewei}");

2.++ 与 --

前加加和后加加的区别,如i++或着++i

如单独使用 不论是前++还是后++,最终的结果都是这个变量+1.

如果配合表达式使用

前++,变量先自加1.然后使用+1后的值参与运算

后++,变量先参与运算,运算完毕后,将这个变量自生+1

//单数使用  前++  后++
int a = 1;
int b = 1;
a++;
++b;
Console.WriteLine(a);//out 2
Console.WriteLine(b);//out 2
int c = 10;
int d = 10;
int e = ++c;
int f = d++;
Console.WriteLine(e);//out 11
Console.WriteLine(f);//out 10
Console.WriteLine(d);//out 11

前- -和后--同上。

3.一元运算符与二元运算符

对于++和--这种只需要一个操作符就能完成的运算,我们称之为一元运算符

而+ - * / $ 这种需要 两个或着两个以上的操作数才能完成运算的操作符成为二元运算符。

4.复合赋值运算符

+= -= *= /= %=

a+= 10; 效果等同于 a = a+10;

5.表达式

由运算符相连的式子就叫做表达式。

posted @ 2022-06-20 01:36  元素-  阅读(32)  评论(0)    收藏  举报