嵌套 if-else
本课属于 Coddy C# 学习旅程的“基础知识”单元。第 30 课,共 69 课。
我们可以在彼此内部嵌套 if-else 语句。这样就能创建分层的决策结构。
例如:
if (age > 18) {
if (hasLicense) {
Console.WriteLine("You can drive");
} else {
Console.WriteLine("Get a license first");
}
} else {
Console.WriteLine("Too young to drive");
}
它可以无限嵌套:
if (condition1) {
if (condition2) {
if (condition3) {
// 如果 condition1、condition2 和 condition3 都为真
...
}
}
}没有花括号时,else 会与它上方最近的、还没有对应 else 的 if 配对:
if (age > 18)
if (hasLicense)
Console.WriteLine("You can drive");
else
Console.WriteLine("Get a license first");这里的 else 属于 if (hasLicense),无论缩进看起来如何。使用花括号可以让配对关系更清楚。
挑战
入门创建一个程序,检查某人是否可以乘坐过山车。要求如下:
- 年龄必须至少为 12 岁
- 身高必须超过 150cm
- 如果满足以上两项要求但未满 15 岁,则需要成人陪同
根据以下情况,将 status 变量设为对应的字符串:
- 年龄太小:
Sorry, you're too young - 身高不够:
Sorry, you're not tall enough - 未满 15 岁且没有成人陪同:
Sorry, you need an adult with you - 未满 15 岁且有成人陪同:
You can ride with adult supervision! - 年满 15 岁且身高足够:
You can ride by yourself!
亲手试试
using System;
class Program {
public static void Main(string[] args) {
int age = int.Parse(Console.ReadLine()); // 不要修改这一行
int height = int.Parse(Console.ReadLine()); // 不要修改这一行
bool hasAdult = bool.Parse(Console.ReadLine()); // 不要修改这一行
string status = "";
// 在下面编写你的代码
// 不要修改这一行以下的代码
Console.WriteLine(status);
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: C# 在线编译器