Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading