Skip to content

猜数游戏

rs
use std::io;
use rand::Rng;
use std::cmp::Ordering;

fn main() {
    println!("猜数!!");
    
    let secret_number = rand::thread_rng().gen_range(1..=100);
    
    // println!("我生成好了一个秘密数字 {secret_number}");
    
    loop {
        println!("输入你猜的");
    
        let mut guess = String::new();
    
        io::stdin()
            .read_line(&mut guess)
            .expect("read line 的时候出错了");
    
        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;
            }
        }
    
        // println!("你猜的是:{}", guess);
    }
}
toml
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021"

[dependencies]
rand    = "0.8.5"

© thebestxt.cc
辽ICP备16009524号-8
本站所有文章版权所有,转载请注明出处