Here’s a Rust program that defines a Fibonacci function and calls it:
fn main() {
// Prompt the user to enter a positive integer
println!("Enter a positive integer:");
let mut input = String::new();
// Read the user's input
std::io::stdin().read_line(&mut input).expect("Failed to read input");
// Parse the input as a u32 (unsigned 32-bit integer)
let n: u32 = match input.trim().parse() {
Ok(num) => num,
Err(_) => {
// Handle invalid input
println!("Invalid input. Please enter a positive integer.");
return;
}
};
// Calculate the nth Fibonacci number using the recursive fib function
let result = fib(n);
// Print the result
println!("The {}th Fibonacci number is {}", n, result);
}
// Define the recursive Fibonacci function
fn fib(n: u32) -> u32 {
// Base cases:
if n == 0 {
return 0;
} else if n == 1 {
return 1;
} else {
// Recursively calculate the Fibonacci numbers
return fib(n - 1) + fib(n - 2);
}
}
Explanation:
std::io
module for input/output operations.std::io::stdin().read_line()
.u32
integer using parse()
.match
.fib
function to calculate the Fibonacci number.To run this program:
main.rs
.rustc main.rs
to compile the code../main
to execute the program.