Menu
CoddyTech

嵌套 If-Else

本课属于 Coddy Rust 学习旅程的“基础知识”单元。第 28 课,共 75 课。

我们可以将 if / else if / else 语句相互嵌套。这样就能创建分层的决策结构。

例如:

if age > 18 {
    if hasLicense {
        println!("You can drive");
    } else {
        println!("Get a license first");
    }
} else {
    println!("Too young to drive");
}

它可以无限嵌套:

if condition1 {
	if condition2 {
		if condition3 {
		    // 如果 condition1、condition2 和 condition3 都为真
		    ...
		}
	}
}
challenge icon

挑战

入门

创建一个程序,检查某人是否可以乘坐过山车。要求如下:

  • 年龄必须至少为 12 岁
  • 身高必须超过 150cm
  • 如果满足这两项要求,但年龄未满 15 岁,则需要成人陪同

针对每种情况,准确输出以下消息:

  • 如果年龄太小: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!

亲手试试

use std::io;

fn main() {
    let mut age_input = String::new();
    let mut height_input = String::new();
    let mut adult_input = String::new();
    
    io::stdin().read_line(&mut age_input).unwrap();
    io::stdin().read_line(&mut height_input).unwrap();
    io::stdin().read_line(&mut adult_input).unwrap();
    
    let age: i32 = age_input.trim().parse().unwrap();
    let height: i32 = height_input.trim().parse().unwrap();
    let has_adult: bool = adult_input.trim().parse().unwrap();

    // 在下方编写你的代码
    
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

基础知识中的所有课

自己练习: Rust 在线编译器