this post was submitted on 24 Dec 2024
33 points (100.0% liked)

Rust

6244 readers
16 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

[email protected]

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 2 years ago
MODERATORS
 

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 are viewing a single comment's thread
view the rest of the comments
[โ€“] [email protected] 3 points 4 weeks ago (1 children)

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.

[โ€“] [email protected] 1 points 4 weeks ago

Thanks, I will keep that in mind.