控制流
在 C 中,控制流通过各种控制结构控制执行路径,如条件语句(if,else,switch)和循环(for,while,do-while)。
If Else
#include <stdio.h>
int main() {
int a = 58;
if (a == 0) printf("a is 0\n");
else if (a < 0) printf("a is negative\n");
else {
printf("a is positive\n");
}
return 0;
}
Switch
swtich 快速跳转到匹配的值并执行其分支。
#include <stdio.h>
int main() {
int dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
printf("Sunday\n");
break;
case 2:
printf("Monday\n");
break;
case 3:
printf("Tuesday\n");
break;
case 4:
printf("Wednesday\n");
break;
case 5:
printf("Thursday\n");
break;
case 6:
printf("Friday\n");
break;
case 7:
printf("Saturday\n");
break;
default:
printf("Invalid number.\n");
}
return 0;
}
For 循环
在 for 循环中,初始化、条件 和 更新 表达式 在括号内指定。只要条件为真,就会重复执行循环体。
#include <stdio.h>
int main() {
int sum = 0;
for (int j = 1; j <= 10; ++j) {
sum += j;
}
printf("Sum of numbers from 1 to 10: %d\n", sum);
return 0;
}
While 循环
在 while 循环中,在进入循环之前评估条件,只要条件为真,循环就会继续执行。
#include <stdio.h>
int main() {
int j = 1;
int sum = 0;
while (j <= 10) {
sum += j;
++j;
}
printf("Sum of numbers from 1 to 10: %d\n", sum);
return 0;
}
Do While 循环
在 do-while 循环中,至少会执行一次循环体,然后在每次迭代后检查条件。如果条件为真,则继续循环;否则,它终止。
do {
sum += count;
++count;
} while (count <= 10);
Goto
C 中的 goto 语句允许将控制转移到程序的任意标记处。虽然有时候很高效,但是通常不建议使用,因为它很可能导致代码难以理解和维护。
#include <stdio.h>
int main() {
int choice;
menu: // 'menu' 标记
printf("Menu:\n");
printf("1. Option 1\n");
printf("2. Option 2\n");
printf("3. Exit\n");
printf("Enter your choice (1-3): ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("You selected Option 1.\n");
goto menu;
case 2:
printf("You selected Option 2.\n");
goto menu;
case 3:
printf("Exiting the program.\n");
break;
default:
printf("Invalid choice.\n");
goto menu;
}
return 0;
}
三元运算符
C 中的三元运算符(? :)是一种简洁的编写简单条件表达式的方法。它接受三个操作数:条件,条件为 true 返回的值,条件为 false 返回的值。
#include <stdio.h>
int main() {
int number = 58;
// 使用三元运算符根据数值的符号赋值消息
// 可以将一个三元运算符嵌套到另一个中
const char *message = (number > 0) ? "Positive" : (number < 0) ? "Negative" : "Zero";
printf("The number is %s.\n", message);
return 0;
}
代码挑战
编写一个C程序,使用三元运算符确定并打印相应的字母等级。
评分标准:
90-100: A 80-89: B 70-79: C 60-69: D 0-59: F
Loading...
> 此处输出代码运行结果