hello,
last time I made a fibonacci series generator in Rust and now I have made something different :)
use std::io;
fn main() {
let mut input: String = String::new();
let stdin = io::stdin();
let x = rand::random::<u32>() % 101;
let mut attempts = 0;
loop {
println!("Guess a number from 0 to 100:");
stdin.read_line(&mut input);
input = input.to_string().replace("\n", ""); // removing the \n
let user_input: u32 = input.parse::<u32>().unwrap();
if x == user_input {
println!("You won! attempts: {attempts}");
break;
}
else if x < user_input {
println!("too big");
attempts += 1;
}
else {
println!("too small");
attempts += 1;
}
input.clear()
}
}
feel free to give me suggestion :)
You shouldn’t use modulo to get a random number in a specific range (solution already in another comment). Reason is that numbers below 64 will be twice as likely as number 64-101 (in your example) due to how binary numbers and modulo works.
This is obviously no real issue for this game, just keep in mind that you shouldn’t implement something like that (random ranges) yourself, this is especially true for crypto related things.
Thanks, I will keep that in mind.