Fibonacci sequence (beginner asking for help)

So I figured this would be a good place to start to familiarize myself with the language at a beginners level, as many have suggested.


fn main() {
    println!("Fibonacci Sequence! I'll print numbers in the fibonacci sequence up to and/or including the number you select.");
    let mut input = String::new();
    loop {
        println!("Enter a number!");
        io::stdin()
            .read_line(&mut input)
            .expect("Failed to read line");

        let input: u32 = match input.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };
        fibonacci(input);
    }

}

fn fibonacci (end: u32) {
    let mut x = 0;
    let mut y = 1;
    loop {

        let z = x + y;
        if z >= end {break};

        println!("{}", z);
        x = y;
        y = z;

    }
}

this is the code i wrote. I'm not really worried about optimization or speed right now (thought i'm not averse to advice in that direction!) my question is why the fibonacci function only works the first time i run it. Every other time i input a number, it just resets the loop without printing out any numbers.

It's probably because read_line will append to the string, not overwrite it. So on future runs, the input will be something like "40\n60\n", which you trim to "40\n60", and this is not a valid integer. However your only error handling is to continue around the loop again. May be a good idea to add a println in that error?

Anyway, you want this:

println!("Enter a number!");
input.clear();
io::stdin()
    .read_line(&mut input)
    .expect("Failed to read line");

Also please check out:

2 Likes

Thanks for the response! Is that something that i could learn from std::io's documentation? Also, if i wanted to both continue and println, would i use brackets to do that, or a comma, or something else? Say if i did something like
Err(_) => println!("You must enter a number, like so '46'."), continue,
would that work?
Any additional reading you could suggest would be appreciated as well.

Yes, if you look up read_line in the documentation, it has this line:

This function will read bytes from the underlying stream until the newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes up to, and including, the delimiter (if found) will be appended to buf.

As for the match, you need a block.

let input: u32 = match input.trim().parse() {
    Ok(num) => num,
    Err(_) => {
        println!("oops");
        continue;
    },
};
1 Like

Sweet. I'll make sure to check out the documentation first next time.

1 Like