求斐波那契数列c语言
时间: 2024-04-21 11:19:53 浏览: 97
以下是三种用C语言实现斐波那契数列的方法[^1]:
1. 递归方法:
```c
#include <stdio.h>
int Fib(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return Fib(n - 1) + Fib(n - 2);
}
}
int main() {
int n = 0;
scanf("%d", &n);
int ret = Fib(n);
printf("%d\n", ret);
return 0;
}
```
2. 非递归方法:
```c
#include <stdio.h>
int Fib(int n) {
int a = 1, b = 1, c = 0;
if (n == 1 || n == 2) {
return 1;
}
for (int i = 3; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
int main() {
int n = 0;
scanf("%d", &n);
int ret = Fib(n);
printf("%d\n", ret);
return 0;
}
```
3. 数组方法:
```c
#include <stdio.h>
int Fib(int n) {
int arr[n];
arr[0] = 1;
arr[1] = 1;
for (int i = 2; i < n; i++) {
arr[i] = arr[i - 1] + arr[i - 2];
}
return arr[n - 1];
}
int main() {
int n = 0;
scanf("%d", &n);
int ret = Fib(n);
printf("%d\n", ret);
return 0;
}
```
阅读全文