学习内容如下:
- BOOL类型
- 关系运算符
- 逻辑运算符
- if else
- switch case
其中最重要的是if语句,应用范围广,使用频率也高。
一.BOOL类型:
BOOL是表示非真即假的数据类型,占内存中一个字节,存储的数据为YES和NO,
YES = 1,NO = 0;
二.关系运算符
operator | name |
---|---|
> | 大于 |
< | 小于 |
== | 等于 |
>= | 大于等于 |
<= | 小于等于 |
!= | 不等于 |
关系运算符组成的式子为关系表达式,其结果为BOOL类型的数据
例子:
- 输出两个数中较大的一个
int a = 0, b = 0, max = 0;
printf("please enter two numbers\n");
scanf("%d%d", &a, &b);
max = a > b ? a : b;
printf("max = %d\n", max);
- 输出三个数中较大的一个
int a = 0, b = 0, c = 0, max = 0;
printf("please enter three numbers\n");
scanf("%d%d%d",&a, &b, &c);
max = a > b ? a : b;
max = max > c ? max : c;
printf("max = %d\n", max);
三.逻辑运算符
operator | name | result |
---|---|---|
&& | 逻辑与 | 逻辑与运算符两端的表达式都为真,则为真,否则为假 |
丨丨 | 逻辑或 | 逻辑或运算符两端的表达式都为假,则为假 |
! | 逻辑非 | 原有为真,非后为假。原有为假,非后为真 |
- 逻辑与运算
int a = 1, b = 2;
BOOL result = (a > b) && (a < b);
printf("result = %d\n", result);
- 逻辑或运算
int a = 1, b = 2;
BOOL result = (a > b) || (a < b);
printf("result = %d\n", result);
- 逻辑非运算
int a = 1, b = 2;
BOOL result = !(a > b);
printf("result = %d\n", result);
逻辑运算的短路
逻辑与短路
左侧表达式为假,右侧不参与运算
int a = 1, b = 2, c = 0; BOOL result = (a > b) && c++; printf("result = %d\n", result); printf("c = %d\n", c); result = 0; c = 0
逻辑或短路
左侧表达式为真,右侧不参与运算
int a = 1, b = 2, c = 0; BOOL result = (a < b) || c++; printf("c = %d\n", c); result = 1; c = 0
四.if else
首先了解一下C语言的程序结构:
1. 顺序结构:main函数是程序的主入口,程序从上至下,从左至右依次执行;
2. 分支结构:程序执行到某个位置,进行条件判断,根据不同的结果,执行不同的操作;
3. 循环结构:程序执行到某个位置,重复执行某个操作;
if语句有三种表达形式:
1. if(条件表达式){
语句;
}
2. if(条件表达式){
语句1;
} else {
语句2;
}
3. if(条件表达式1){
语句1;
} else if(条件表达式2){
语句2;
} else {
语句3;
}
五.switch case
int season = 0;
printf("please enter a number between 1 and 4\n");
scanf("%d", &season);
switch (season) {
case 1:
printf("spring\n");
break;
case 2:
printf("summer\n");
break;
case 3:
printf("autumn\n");
break;
case 4:
printf("winter\n");
break;
default:
printf("please enter a number between 1 and 4\n");
break;
}
习题
- 判断奇数还是偶数
int a = 0;
printf("please enter a number\n");
scanf("%d", &a);
if(a % 2 == 0){
printf("this is an even number\n");
} else {
printf("this is an odd number\n");
}
- 从键盘输入一个加减乘除的式子,输出结果
float number1 = 0.0, number2 = 0.0, result = 0.0;
char operator = 0;
printf("please give me a formula like '1 + 1'\n");
scanf("%f%c%f", &number1, &operator, &number2);
switch (operator) {
case '+':
result = number1 + number2;
break;
case '-':
result = number1 - number2;
break;
case '*':
result = number1 * number2;
break;
case '/':
resulst = number1 / number2;
break;
default:
break;
}
printf("result = %f\n", result);
- 从键盘输入字符,则输出字符,从键盘输入数字,则输出数字
int a = 0;
char b = 0;
if(scanf("%d", &a)){
printf("%d\n", a);
} else if(scanf("%c", &b)){
printf("%c\n", b);
}