rust猜数字小游戏
use rand::Rng; // 随机数
use std::cmp::Ordering; //macth
use std::io; //io
fn main() {
//生成随机数
let s = rand::thread_rng().gen_range(1..101);
loop {
println!("请输入:");
//io流读取输入文字
let mut guesst = String::new();
io::stdin().read_line(&mut guesst).expect("无法读取行");
println!("你猜测的数是:{} ", guesst);
//转换为int类型
let guesst: u32 = match guesst.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("输入错误");
continue;
}
};
//循环判断输入的数字是否正确
match guesst.cmp(&s) {
Ordering::Less => println!("Too small"),
Ordering::Equal => {
println!("Yes win");
break;
}
Ordering::Greater => println!("Too big"),
}
}
}
评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果