3.guessing_game 猜数游戏

This commit is contained in:
Shikong 2022-06-26 19:53:13 +08:00
parent c9cb4d209e
commit 000b35157a
2 changed files with 37 additions and 8 deletions

View File

@ -6,3 +6,4 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
rand = "0.8.4"

View File

@ -1,11 +1,18 @@
// 默认 导入 prelude // 默认 导入 prelude
use std::cmp::Ordering;
// 使用 库 // 使用 库
use std::io; use std::io;
use rand::Rng; // trait
fn main() { fn main() {
println!("猜数游戏"); println!("猜数游戏");
let secret_number = rand::thread_rng() // 随机数生成器
.gen_range(1..100); // 生成随机数
println!("随机数为: {}", secret_number);
// 声明变量 // 声明变量
// let foo = 1; // let foo = 1;
// let bar = foo; // immutable // let bar = foo; // immutable
@ -13,14 +20,35 @@ fn main() {
// rust 中 所有变量默认为不可变 // rust 中 所有变量默认为不可变
// foo = 2; // 抛错 // foo = 2; // 抛错
// 声明变量时 添加 mut 关键字 为可变变量 loop {
let mut guess = String::new(); // 创建空字符串 实例 println!("请猜一个数");
// 声明变量时 添加 mut 关键字 为可变变量
let mut guess = String::new(); // 创建空字符串 实例
io::stdin() io::stdin()
.read_line(&mut guess) .read_line(&mut guess)
// read_line 返回 io::Result Ok, Err // read_line 返回 io::Result Ok, Err
// 捕获异常 // 捕获异常
.expect("读取失败"); .expect("读取失败");
println!("猜测的值为 {}",guess) println!("猜测的值为 {}", guess.trim());
// shadow 隐藏
let guess: u32 = match guess.trim().parse() { // 处理错误
Ok(num) => num,
Err(_) => {
println!("请输入数字");
continue
},
};
match guess.cmp(&secret_number) {
Ordering::Less => println!("太小了"),
Ordering::Greater => println!("太大了"),
Ordering::Equal => {
println!("猜对了");
break;
},
}
}
} }