我尝试用 Rust 解决斐波那契数列问题,但不幸的是它总是返回 2^n 的指数。这是我的代码:
use std::io;
// Fibonacci Series Number
// F(n) = 1,1,2,3,5,8,13,....(n-1),((n-1)+n)
// where, n >= 0
fn fibo(mut n: u32) -> u32 {
let mut _prev: u32 = 0;
let mut current: u32 = 1;
let mut next: u32 = 1;
let mut sum: u32 = 1;
if n <= 0 {
return 0;
}
if n == 1 || n == 2 {
return 1;
};
if n > 2 {
while n >= 1 {
current = next;
_prev = current;
sum = _prev + current;
next = sum;
n -= 1;
}
next
} else {
return 1;
}
}
fn main() {
println!("Fibo of nth: What is nth?: n --> ");
let mut n = String::new();
io::stdin().read_line(&mut n).expect("Invalid input");
let n: u32 = n
.trim()
.parse()
.expect("Not a number. Please type a number");
let fibo = fibo(n);
println!("Fibo of {n}: {fibo}");
}
这是输出:
我尝试返回next,这将是第n个斐波那契数的答案,但它每次都给我2^n。
您的更新如下:
current = next;
_prev = current;
sum = _prev + current;
next = sum;
这些并不是同时发生的,而是一步一步发生的。因此,在第一步
current = next
之后,current
就会被覆盖。然后,当您执行 _prev = current
... _prev
时,also 等于 next
。这意味着 sum = _prev + current
只是 sum = 2*next
。那么 next = sum
本质上就相当于 next = 2*next
,这就是为什么你会看到 2 的幂。
您可以做一个更简单的更新,也只需要 2 个可变变量,
current
和 next
:
let sum = current + next;
current = next;
next = sum;