如何用c语言解决斐波那契数
时间: 2024-10-06 08:00:58 浏览: 12
在C语言中,你可以通过递归、循环或者动态规划的方式来计算斐波那契数列。这里我会展示三种常见的方法:
1. **递归**:
```c
#include <stdio.h>
int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
int main() {
int num = 10; // 要求的斐波那契数的位置
printf("Fibonacci of %d is %d\n", num, fibonacci(num));
return 0;
}
```
2. **循环**:
```c
#include <stdio.h>
int fibonacci(int n) {
int a = 0, b = 1, c;
if (n == 0) return a;
for (int i = 2; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}
int main() {
int num = 10;
printf("Fibonacci of %d is %d\n", num, fibonacci(num));
return 0;
}
```
3. **动态规划** (存储中间结果):
```c
#include <stdio.h>
int fibonacci(int n) {
int fib[n+1];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
return fib[n];
}
int main() {
int num = 10;
printf("Fibonacci of %d is %d\n", num, fibonacci(num));
return 0;
}
```
阅读全文