rustwhile-loopfibonacci

Fibonacci series issue in rust


pub fn fibonacci() {
    println!("Please enter the number");
    let mut n1 = 0;
    let mut n2 = 1;
    let mut n3 = 0;
    let mut number = String::new();
    std::io::stdin().read_line(&mut number).expect("Failed to read line");
    let number: u32 = number.trim().parse().expect("Please enter a valid number");

    println!("The number is {}", number);

    let mut count = number - 2;
    println!("The fibonacci number is {}", n1);
    println!("The fibonacci number is {}", n2);
    while count != 0 {
        n3 = n1 + n2;
        n1 = n2;
        n2 = n3;

        count -= 1;
        // println!("The fibonacci number is {}", n3);
    }
    println!("The fibonacci number is {}", n3);
}

I tried to print the fibonacci series. But i am not getting exact fibonacci number but one less that that for example If i enter the number 6 and it should return 8 as the 8 is the 6th fibonacci number. But I am getting 5. is there issue in my code? if yes please provide me the help.

I found that if I have passed count = number - 1 . It provides me the answer but I am still confused. Can anyone explain me this or anyone help me understand the issue in the code .

if count = number -1 is set the value will give the exact number. But i could not understand why is it happening any one can explain me this ?


Solution

  • The issue in your code lies in how you init your count variable

    let mut count = number - 2; 
    

    you are skipping the first 2 fibonacci numbers 0 and 1 change the line to

    let mut count = number - 1;