1.算术操作符:+、-、*、/、%
在写代码时候,⼀定会涉及到计算。
C语⾔中为了方便运算,提供了⼀系列操作符,其中有⼀组操作符叫:算术操作符。分别是: + - * / % ,这些操作符都是双目操作符(有两个操作数)。
注:操作符也被叫做:运算符,是不同的翻译,意思是⼀样的。
1.1 + -
+ 和 - ⽤来完成加法和减法。
#include <stdio.h>
int main()
{
int x = 4 + 22;
int y = 61 - 23;
printf("%d ", x);
printf("%d ", y);
return 0;
}
1.2 *
*用来完成乘法
#include <stdio.h>
int main()
{
int num = 5 * 5;
printf("%d", num);
return 0;
}
1.3 /
#include <stdio.h>
int main()
{
float x = 6 / 4;
int y = 6 / 4;
printf("%f\n", x); // 输出 1.000000
printf("%d\n", y); // 输出 1
return 0;
}
#include <stdio.h>
int main()
{
float x = 6.0 / 4;
int y = 6 / 4;
printf("%f\n", x); // 输出 1.500000
printf("%d\n", y); // 输出 1
return 0;
}
#include <stdio.h>
int main()
{
int score = 5;
score = (score / 20) * 100;
return 0;
}
1.4 %
#include <stdio.h>
int main()
{
int x = 6 % 4; // 2
return 0;
}
如果有负数呢
#include <stdio.h>
int main()
{
printf("%d ", 11 % -5); // 1
printf("%d ", -11 % -5); // -1
printf("%d ", -11 % 5); // -1
return 0;
}
由结果可以看出,,第⼀个运算数的正负号( 11 或 -11 )决定了结果的正负号。
2.赋值操作符:=和复合赋值
在变量创建的时候给⼀个初始值叫初始化,在变量创建好后,再给⼀个值,这叫赋值。
int a = 100;//初始化
a = 200;//赋值
(!注:=为赋值操作符,不能误认为是数学上的等号,C语言有自己的“等于”)
2.1连续赋值
赋值操作符也可以连续赋值,如:
int a = 3;
int b = 5;
int c = 0;
c = b = a + 3;//连续赋值,从右向左依次赋值的。
2.2复合赋值符
在写代码时,我们经常可能对⼀个数进行自增、自减的操作,如下代码:
int a = 10;
a = a+3;
a = a-2;
int a = 10;
a += 3; 等价于a = a+3;
a -= 2; 等价于a = a-2;
+= -=
*= /= %=
//下⾯的操作符后期讲解
>>= <<=
&= |= ^=
3.单⽬操作符:++、--、+、-
3.1++和--
3.1.1前置++
int a = 10;
int b = ++a;//++的操作数是a,是放在a的前⾯的,就是前置++
int a = 10;
a = a+1;
b = a;
3.1.2后置++
int a = 10;
int b = a++;//++的操作数是a,是放在a的后⾯的,就是后置++
计算口诀:先使用,后+1
a原来是10,先使⽤,就是先赋值给b,b得到了10,然后再+1,然后a变成了11,所以直接结束后a是11,b是10,相当于这样的代码:
int a = 10;
int b = a;
a = a+1;
3.1.3前置--
会了++那么--自然不在话下,简直是买一送一的买卖
int a = 10;
int b = --a;//--的操作数是a,是放在a的前⾯的,就是前置--
结果a和b都是9
3.1.4后置--
计算口诀:先使用,后-1
int a = 10;
int b = a--;//--的操作数是a,是放在a的后⾯的,就是后置--
3.2+ 和 -
int a = +10; 等价于 int a = 10;
4.字符和ASCII编码
参考:https://en.cppreference.com/w/cpp/language/ascii
#include <stdio.h>
int main()
{
printf("%c ", 'Q');
printf("%c ", 81);//这⾥的81是字符Q的ASCII码值,也是可以正常打印的
return 0;
}
5.转义字符
如果你看一些高手写代码会发现 \n 这些没见过的符号,这些就是转义字符,转义 字符顾名思义:转变原来的意思的字符,那转义字符有什么用呢
#include <stdio.h>
int main()
{
printf("abcndef");
return 0;
}
如果我们修改⼀下代码,在 n 的前⾯加上 \ ,变成如下代码:
#include <stdio.h>
int main()
{
printf("abc\ndef");
return 0;
}
输出结果:

6.字符串和\0
我们知道了什么是字符,那字符串自然就是字符串连起来
C语⾔中字符是⽤单引号 括起来的,而字符串则是用双引号,如:"hello World" 就是⼀个字符串
字符串的打印格式可以使⽤ %s 来指定,也可以直接打印如下:
#include <stdio.h>
int main()
{
printf("%s\n", "hello World");
printf("hello world");
return 0;
}
让我们看看字符串在内存中是如何存储的吧

#include <stdio.h>
int main()
{
printf("%s\n", "hello\0 World");
printf("hello world");
return 0;
}
运行看结果:

可以看到因为我们手动添加了 \0 让printf()函数认为字符串结束从而没有打印后面的“World”
7.注释
7.1注释
C语言有两种注释方法
7.1.1 /**/式
/* 注释 */
/*
这是⼀⾏注释
*/
7.1.2 // 式
// 这是⼀⾏注释
int x = 1; // 这也是注释
printf("// hello /* world */ ");

539

被折叠的 条评论
为什么被折叠?



