龙空技术网

Rust基础:实现一个猜数字游戏

科技树乱点 127

前言:

现时兄弟们对“c语言编程猜数游戏代码”大概比较关切,各位老铁们都想要学习一些“c语言编程猜数游戏代码”的相关文章。那么小编同时在网上网罗了一些对于“c语言编程猜数游戏代码””的相关知识,希望姐妹们能喜欢,姐妹们快快来学习一下吧!

#挑战30天在头条写日记#

原始内容来源:

需要提前了解的内容

在阅读本文之前,请确认已经了解下面的知识:

什么是Rust?是什么是Cargo?怎么构建、运行Rust项目?使用Rust编写一个猜数字游戏

创建一个新项目:

cargo new guessing_gamecd guessing_game

编辑Cargo.toml文件

[package]name = "guessing_game"version = "0.1.0"edition = "2021"# See more keys and their definitions at [dependencies]
package字段:当前项目的名称,版本号等信息dependencies字段:项目依赖,当前默认为空

编辑主要代码逻辑文件src/main.rs:

fn main() {  println!("Hello, world!");}

运行项目:

cargo run

引入标准输入输出库:

use std::io;fn main() {    println!("Guess the number!");    println!("Please input your guess.");    let mut guess = String::new();    io::stdin()        .read_line(&mut guess)        .expect("Failed to read line");    println!("You guessed: {guess}");}

生成随机数,需要添加依赖:

[dependencies]rand = "0.8.5"
use std::io;use rand::Rng;fn main() {  println!("Guess the number!");    let secret_number = rand::thread_rng().gen_range(1..=100);  println!("The secret number is: {secret_number}");  println!("Please input your guess.");    let mu guess = String::new();    id::stdin()    .read_line(&mut guess)    .expect("Failed to read line");    println!("You guessed: {guess}");}

比较猜测数字是否正确:

use std::io;use rand::Rng;fn main() {  println!("Guess the number!");    let secret_number = rand::thread_rng().gen_range(1..=100);  println!("The secret number is: {secret_number}");  println!("Please input your guess.");    let mu guess = String::new();    id::stdin()    .read_line(&mut guess)    .expect("Failed to read line");    println!("You guessed: {guess}");    match guess.cmp(&secret_number) {    Ordering::Less => println!("Too small!"),    Ordering::Greater => println!("Too big!"),    Ordering::Equal => println!("You win!"),  }}

`guess.cmp`这段代码会因为类型和函数签名不一致报错:

$ cargo build   Compiling libc v0.2.86   Compiling getrandom v0.2.2   Compiling cfg-if v1.0.0   Compiling ppv-lite86 v0.2.10   Compiling rand_core v0.6.2   Compiling rand_chacha v0.3.0   Compiling rand v0.8.5   Compiling guessing_game v0.1.0 ()error[E0308]: mismatched types  --> src/main.rs:22:21   |22 |     match guess.cmp(&secret_number) {   |                 --- ^^^^^^^^^^^^^^ expected struct `String`, found integer   |                 |   |                 arguments to this function are incorrect   |   = note: expected reference `&String`              found reference `&{integer}`note: associated function defined here  --> /rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/cmp.rs:783:8For more information about this error, try `rustc --explain E0308`.error: could not compile `guessing_game` due to previous error

需要修改成下面的代码:

use std::io;use std::cmp::Ordering;use rand::Rng;fn main() {  println!("Guess the number!");  let secret_number = rand::thread_rng().gen_range(1..=100);  println!("The secret number is: {secret_number}");  println!("Please input your guess.");  let mut guess = String::new();  io::stdin()    .read_line(&mut guess)    .expect("Failed to read line");  let guess: u32 = guess.trim().parse().expect("Please try a number");  println!("You guessed: {guess}");  match guess.cmp(&secret_number) {    Ordering::Less => println!("Too small!"),    Ordering::Greater => println!("Too big!"),    Ordering::Equal => println!("You win!"),  }}

通过循环允许多次输入:

use std::io;use std::cmp::Ordering;use rand::Rng;fn main() {  println!("Guess the number!");  let secret_number = rand::thread_rng().gen_range(1..=100);  println!("The secret number is: {secret_number}");  loop {    println!("Please input your guess.");    let mut guess = String::new();    io::stdin()      .read_line(&mut guess)      .expect("Failed to read line");      let guess: u32 = guess.trim().parse().expect("Please try a number");      println!("You guessed: {guess}");      match guess.cmp(&secret_number) {        Ordering::Less => println!("Too small!"),        Ordering::Greater => println!("Too big!"),        Ordering::Equal => println!("You win!"),      }  }}

上面的代码运行后需要通过强制退出(例如mac下按`control+c`键)。

添加正常的退出逻辑:

use std::io;use std::cmp::Ordering;use rand::Rng;fn main() {  println!("Guess the number!");  let secret_number = rand::thread_rng().gen_range(1..=100);  println!("The secret number is: {secret_number}");  loop {    println!("Please input your guess.");    let mut guess = String::new();    io::stdin()      .read_line(&mut guess)      .expect("Failed to read line");      let guess: u32 = guess.trim().parse().expect("Please try a number");      println!("You guessed: {guess}");      match guess.cmp(&secret_number) {        Ordering::Less => println!("Too small!"),        Ordering::Greater => println!("Too big!"),        Ordering::Equal => {          println!("You win!");          break;        }      }  }}

上面这段代码还有个问题,假如用户输入的不是数字,会导致整个程序直接崩溃。

use std::io;use std::cmp::Ordering;use rand::Rng;fn main() {  println!("Guess the number!");  let secret_number = rand::thread_rng().gen_range(1..=100);  println!("The secret number is: {secret_number}");  loop {    println!("Please input your guess.");    let mut guess = String::new();    io::stdin()      .read_line(&mut guess)      .expect("Failed to read line");      let guess: u32 = match guess.trim().parse() {        Ok(num) => num,        Err(_) => continue,      };      println!("You guessed: {guess}");      match guess.cmp(&secret_number) {        Ordering::Less => println!("Too small!"),        Ordering::Greater => println!("Too big!"),        Ordering::Equal => {          println!("You win!");          break;        }      }  }}

这样即使用户输入不是数字,也不会导致程序直接崩溃了。

标签: #c语言编程猜数游戏代码