3.guessing_game 猜数游戏
This commit is contained in:
parent
c9cb4d209e
commit
000b35157a
@ -6,3 +6,4 @@ edition = "2021"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
rand = "0.8.4"
|
@ -1,11 +1,18 @@
|
||||
// 默认 导入 prelude
|
||||
|
||||
use std::cmp::Ordering;
|
||||
// 使用 库
|
||||
use std::io;
|
||||
use rand::Rng; // trait
|
||||
|
||||
fn main() {
|
||||
println!("猜数游戏");
|
||||
|
||||
let secret_number = rand::thread_rng() // 随机数生成器
|
||||
.gen_range(1..100); // 生成随机数
|
||||
|
||||
println!("随机数为: {}", secret_number);
|
||||
|
||||
// 声明变量
|
||||
// let foo = 1;
|
||||
// let bar = foo; // immutable
|
||||
@ -13,6 +20,8 @@ fn main() {
|
||||
// rust 中 所有变量默认为不可变
|
||||
// foo = 2; // 抛错
|
||||
|
||||
loop {
|
||||
println!("请猜一个数");
|
||||
// 声明变量时 添加 mut 关键字 为可变变量
|
||||
let mut guess = String::new(); // 创建空字符串 实例
|
||||
|
||||
@ -22,5 +31,24 @@ fn main() {
|
||||
// 捕获异常
|
||||
.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;
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user