C++ If ... Else 示例
实际应用示例
此示例展示了如何使用 if..else 语句,在用户输入正确密码后"打开门":
示例
int doorCode = 1337;
if (doorCode == 1337) {
cout << "Correct code.The door is now open.";
} else {
cout << "Wrong code.The door remains closed.";
}
亲自试一试 »
此示例展示了如何使用 if..else 来判断一个数字是正数还是负数:
示例
int myNum = 10; // Is this a positive or negative number?
if (myNum > 0) {
cout << "The value is a positive number.";
} else if
(myNum < 0) {
cout << "The value is a negative number.";
} else
{
cout << "The value is 0.";
}
亲自试一试 »
查明某人是否达到投票年龄:
示例
int myAge = 25;
int votingAge = 18;
if (myAge >= votingAge) {
cout << "Old enough to vote!";
} else {
cout << "Not old enough to vote.";
}
亲自试一试 »
判断某人是否达到投票年龄,以及是否为公民(使用嵌套的if语句):
示例
int age = 20;
bool isCitizen = true;
if (age >= 18) {
cout << "Old enough to vote.
";
if (isCitizen) {
cout << "And you are a citizen, so you can vote!
";
} else {
cout << "But you must be a citizen to vote.
";
}
} else {
cout << "Not old enough to vote.
";
}
判断一个数是奇数还是偶数:
示例
int myNum = 5;
if (myNum % 2 == 0) {
cout << myNum << " is even.";
} else {
cout << myNum << " is odd.";
}
亲自试一试 »
查看温度(摄氏度):
示例
int temperature = 30;
if (temperature < 0) {
cout << "It's freezing!
";
} else if (temperature < 20) {
cout << "It's cool.
";
} else {
cout << "It's warm.
";
}
亲自试一试 »

