From 000b35157ad606bb51bac9cce85b37bf62d11a98 Mon Sep 17 00:00:00 2001 From: Shikong <919411476@qq.com> Date: Sun, 26 Jun 2022 19:53:13 +0800 Subject: [PATCH] =?UTF-8?q?3.guessing=5Fgame=20=E7=8C=9C=E6=95=B0=E6=B8=B8?= =?UTF-8?q?=E6=88=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 3.guessing_game/Cargo.toml | 1 + 3.guessing_game/src/main.rs | 44 ++++++++++++++++++++++++++++++------- 2 files changed, 37 insertions(+), 8 deletions(-) diff --git a/3.guessing_game/Cargo.toml b/3.guessing_game/Cargo.toml index 78c94fe..0a6513f 100644 --- a/3.guessing_game/Cargo.toml +++ b/3.guessing_game/Cargo.toml @@ -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" \ No newline at end of file diff --git a/3.guessing_game/src/main.rs b/3.guessing_game/src/main.rs index cc20a20..7553042 100644 --- a/3.guessing_game/src/main.rs +++ b/3.guessing_game/src/main.rs @@ -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,14 +20,35 @@ fn main() { // rust 中 所有变量默认为不可变 // foo = 2; // 抛错 - // 声明变量时 添加 mut 关键字 为可变变量 - let mut guess = String::new(); // 创建空字符串 实例 + loop { + println!("请猜一个数"); + // 声明变量时 添加 mut 关键字 为可变变量 + let mut guess = String::new(); // 创建空字符串 实例 - io::stdin() - .read_line(&mut guess) - // read_line 返回 io::Result Ok, Err - // 捕获异常 - .expect("读取失败"); + io::stdin() + .read_line(&mut guess) + // read_line 返回 io::Result Ok, Err + // 捕获异常 + .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; + }, + } + } }