C If ... Else 示例
实际应用示例
此示例展示了如何使用 if..else 在用户输入正确密码后"打开门":
示例
int doorCode = 1337;
if (doorCode == 1337) {
printf("Correct
code.
The door is now open.");
} else {
printf("Wrong code.
The
door remains closed.");
}
亲自试一试 »
此示例展示了如何使用 if..else 来判断一个数字是正数还是负数:
示例
int myNum = 10; // 这是一个正数还是负数?
if (myNum >
0) {
printf("The value is a positive number.");
} else if (myNum
< 0) {
printf("The value is a negative number.");
} else {
printf("The value is 0.");
}
亲自试一试 »
查询某人是否达到投票年龄:
示例
int myAge = 25;
int votingAge = 18;
if (myAge >= votingAge) {
printf("Old enough to vote!");
} else {
printf("Not old enough
to vote.");
}
亲自试一试 »
判断一个人是否达到投票年龄,以及是否为公民(使用嵌套的if语句):
示例
int age = 20;
bool isCitizen = true;
if (age >= 18) {
printf("Old enough to vote.
");
if (isCitizen) {
printf("And you are a citizen, so you can vote!
");
} else {
printf("But you must be a citizen to vote.
");
}
} else {
printf("Not old enough to vote.
");
}
判断一个数是奇数还是偶数:
示例
int myNum = 5;
if (myNum % 2 == 0) {
printf("%d is even.", myNum);
} else {
printf("%d is odd.", myNum);
}
亲自试一试 »
查看温度(摄氏度):
示例
int temperature = 30;
if (temperature < 0) {
printf("It's freezing!
");
} else if (temperature < 20) {
printf("It's cool.
");
} else {
printf("It's warm.
");
}
亲自试一试 »
系统访问控制示例 - 您必须先登录,然后必须是管理员,或者拥有高安全级别(1 级或 2 级)才能获得访问权限:
示例
bool isLoggedIn = true;
bool isAdmin = false;
int securityLevel = 3; // 1 = highest
if (isLoggedIn && (isAdmin || securityLevel <= 2)) {
printf("Access granted
");
} else {
printf("Access denied
");
}
// 尝试更改 securityLevel 和 isAdmin 参数,以测试不同的结果:
// securityLevel 1 = Access granted
// securityLevel 2 = Access granted
// securityLevel 3 = Access denied
// securityLevel 4 = Access denied
// If isAdmin = true, access is granted.

