Created
April 9, 2022 13:17
-
-
Save uztbt/1c9dd0a8f30aea8b3eb447033d2fd89f to your computer and use it in GitHub Desktop.
An exercise of Chaper 3 of the Book
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io; | |
fn main() { | |
loop { | |
println!("Input a number!"); | |
let mut nth = String::new(); | |
io::stdin() | |
.read_line(&mut nth) | |
.expect("Error in reading nth"); | |
let nth: u32 = match nth.trim().parse() { | |
Ok(n) => n, | |
Err(_) => continue, | |
}; | |
let ans = fib(nth); | |
println!("{}th Fibonacci number is {}", nth, ans); | |
} | |
} | |
// Returns the nth number of the Fibonacci sequence. | |
fn fib(n: u32) -> u64 { | |
match n { | |
0 => 1, | |
1 => 1, | |
m => fib(m - 1) + fib(m - 2), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment