Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Call rand package for random number generation
- extern crate rand;
- use std::io;
- use std::io::Write;
- use rand::Rng;
- fn main() {
- // Set the limit of answer
- const MAX: u32 = 100;
- const MIN: u32 = 1;
- // Set the limit of user input
- let mut upper = MAX;
- let mut lower = MIN;
- // Get a random number between MIN and MAX
- let answer = rand::thread_rng().gen_range(MIN, MAX + 1);
- loop {
- // Prompt for user input
- print!("Input a number ({}-{}):", lower, upper);
- // Flush standard out
- let _ = io::stdout().flush();
- // Receive user input
- let mut input = String::new();
- io::stdin()
- .read_line(&mut input)
- .expect("Failed to read from stdin");
- // Parse integer
- let guess = match input.trim().parse::<u32>() {
- Ok(n) => n,
- Err(_) => {
- println!("Not a valid number");
- continue;
- }
- };
- // Check the range of the guess
- if guess < lower || guess > upper {
- println!("The number should be between {} and {}",
- lower, upper);
- continue;
- }
- // Check whether the guess is correct
- if guess == answer {
- println!("You got it!");
- break;
- } else if guess > answer {
- println!("Too large");
- upper = guess;
- } else { // guess < answer
- println!("Too small");
- lower = guess;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement