C 语言条件语句
在编程中,条件语句用于根据特定条件决定程序的执行路径。C语言提供了多种条件语句,包括if
、else if
、else
和switch
语句。这些语句允许你根据不同的条件执行不同的代码块。
1. if
语句
if
语句是最基本的条件语句。它用于在条件为真时执行一段代码。
语法
c
if (条件) {
// 条件为真时执行的代码
}
示例
c
#include <stdio.h>
int main() {
int number = 10;
if (number > 5) {
printf("Number is greater than 5\n");
}
return 0;
}
输出:
Number is greater than 5
备注
if
语句中的条件必须是一个布尔表达式,即结果为true
或false
。
2. else
语句
else
语句用于在if
条件为假时执行另一段代码。
语法
c
if (条件) {
// 条件为真时执行的代码
} else {
// 条件为假时执行的代码
}
示例
c
#include <stdio.h>
int main() {
int number = 3;
if (number > 5) {
printf("Number is greater than 5\n");
} else {
printf("Number is less than or equal to 5\n");
}
return 0;
}
输出:
Number is less than or equal to 5
3. else if
语句
else if
语句用于在多个条件之间进行选择。它允许你在if
条件为假时检查另一个条件。
语法
c
if (条件1) {
// 条件1为真时执行的代码
} else if (条件2) {
// 条件2为真时执行的代码
} else {
// 所有条件都为假时执行的代码
}
示例
c
#include <stdio.h>
int main() {
int number = 7;
if (number > 10) {
printf("Number is greater than 10\n");
} else if (number > 5) {
printf("Number is greater than 5 but less than or equal to 10\n");
} else {
printf("Number is less than or equal to 5\n");
}
return 0;
}
输出:
Number is greater than 5 but less than or equal to 10
4. switch
语句
switch
语句用于根据变量的值执行不同的代码块。它通常用于替代多个if-else
语句。
语法
c
switch (表达式) {
case 值1:
// 表达式等于值1时执行的代码
break;
case 值2:
// 表达式等于值2时执行的代码
break;
default:
// 表达式不等于任何值时执行的代码
break;
}
示例
c
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
break;
}
return 0;
}
输出:
Wednesday
警告
在switch
语句中,break
语句用于终止switch
语句的执行。如果没有break
,程序将继续执行下一个case
块,直到遇到break
或switch
语句结束。
实际应用场景
案例1:用户输入验证
假设你正在编写一个程序,要求用户输入一个数字,并根据输入的数字输出不同的消息。
c
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number > 0) {
printf("You entered a positive number.\n");
} else if (number < 0) {
printf("You entered a negative number.\n");
} else {
printf("You entered zero.\n");
}
return 0;
}
案例2:菜单选择
假设你正在编写一个简单的菜单程序,用户可以选择不同的选项来执行不同的操作。
c
#include <stdio.h>
int main() {
int choice;
printf("Menu:\n");
printf("1. Option 1\n");
printf("2. Option 2\n");
printf("3. Option 3\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("You selected Option 1.\n");
break;
case 2:
printf("You selected Option 2.\n");
break;
case 3:
printf("You selected Option 3.\n");
break;
default:
printf("Invalid choice.\n");
break;
}
return 0;
}
总结
C语言中的条件语句是控制程序执行流程的重要工具。通过if
、else if
、else
和switch
语句,你可以根据不同的条件执行不同的代码块。掌握这些语句的使用方法,将使你能够编写更加灵活和强大的程序。
附加资源与练习
- 练习1: 编写一个程序,要求用户输入一个年份,判断该年份是否为闰年。
- 练习2: 编写一个程序,要求用户输入一个字符,判断该字符是元音字母还是辅音字母。
提示
尝试自己编写代码并运行,以加深对条件语句的理解。