c语言中如何表示斐波那契数列
时间: 2024-10-11 11:08:10 浏览: 19
在C语言中,斐波那契数列可以使用循环或递归来实现。以下是两种常见的方法:
1. **循环法**(迭代法):
```c
#include <stdio.h>
unsigned long long fib(int n) {
if (n <= 1) return n;
unsigned long long t1 = 0, t2 = 1, nextTerm = 0;
for (int i = 2; i <= n; ++i) {
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return nextTerm;
}
int main() {
int n;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci series up to %d terms:\n", n);
for (int i = 0; i < n; ++i) {
printf("%llu ", fib(i));
}
return 0;
}
```
在这段代码中,我们通过循环不断计算当前和下一个斐波那契数,直到达到指定项数。
2. **递归法**(尽管效率较低,但简洁易懂):
```c
#include <stdio.h>
unsigned long long fib_recursion(int n) {
if (n <= 1)
return n;
return fib_recursion(n - 1) + fib_recursion(n - 2);
}
int main() {
int n;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci series up to %d terms:\n", n);
for (int i = 0; i < n; ++i) {
printf("%llu ", fib_recursion(i));
}
return 0;
}
```
在递归版本中,如果n小于等于1,直接返回n,否则递归地计算前两个数之和。
阅读全文