斐波那契数列c语言程序
时间: 2023-11-20 18:58:48 浏览: 102
以下是三种不同方法实现斐波那契数列的C语言程序:
1. 递归法
```c
#include <stdio.h>
int Fib(int n) {
if (n <= 1) {
return n;
}
return Fib(n - 1) + Fib(n - 2);
}
int main() {
int n;
scanf("%d", &n);
printf("%d", Fib(n));
return 0;
}
```
2. 非递归法
```c
#include <stdio.h>
int Fib(int n) {
int a = 0, b = 1, c, i;
if (n == 0) {
return a;
}
for (i = 2; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}
int main() {
int n;
scanf("%d", &n);
printf("%d", Fib(n));
return 0;
}
```
3. 数组法
```c
#include <stdio.h>
int Fib(int n) {
int i;
int arr[100] = {0, 1, 1};
for (i = 2; i <= n; i++) {
arr[i] = arr[i - 1] + arr[i - 2];
}
return arr[n];
}
int main() {
int n;
scanf("%d", &n);
printf("%d", Fib(n));
return 0;
}
```
阅读全文