用C语言生成斐波那契数列
时间: 2024-12-18 13:31:56 浏览: 7
在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_terms;
printf("Enter the number of terms: ");
scanf("%d", &num_terms);
for (int i = 0; i < num_terms; ++i) {
printf("%d ", fibonacci(i));
}
return 0;
}
```
2. **迭代法**(更高效):
```c
#include <stdio.h>
void print_fibonacci(int n) {
int t1 = 0, t2 = 1, nextTerm;
printf("Fibonacci Series: ");
for (int i = 1; i <= n; ++i) {
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
}
int main() {
int num_terms;
printf("Enter the number of terms: ");
scanf("%d", &num_terms);
print_fibonacci(num_terms);
return 0;
}
```
这两种方法都可以生成指定长度的斐波那契数列。
阅读全文