#include<stdio.h>
//斐波那契数列 1 1 2 3 5 8 13 21 34 55
//三种方法
//第一种:递归,比较繁琐,效率低
/*int fib(int n) {
if (n <= 2) {
return 1;
}
else {
return fib(n - 2) + fib(n - 1);
}
}*/
//第二种
/*int fib(int n) {
if (n <= 2) {
return 1;
}
else{
int a = 1;
int b = 1;
int c = 1;
for (int i = 3; i < n + 1; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
}*/
//第三种
int fib(int n) {
int a = 1;
int b = 1;
int c = 1;
while (n > 2) {
c = a + b;
a = b;
b = c;
n--;
}
return c;
}
int main() {
int n = 0;
scanf_s("%d", &n);
int ret=fib(n);
printf("ret=%d\n", ret);
return 0;
}
斐波那契数列,求第n个数字
于 2023-04-17 11:00:48 首次发布