C语言实现斐波那契数列
时间: 2023-08-04 19:12:53 浏览: 79
斐波那契数列是一组由 0 和 1 开始的数字,后续的数字都是由前两个数字相加而来。C语言实现斐波那契数列可以使用循环或递归的方式实现。
1. 循环实现:
```c
#include <stdio.h>
int main() {
int n, i, t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 1; i <= n; ++i) {
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
```
2. 递归实现:
```c
#include <stdio.h>
int fibonacci(int n);
int main() {
int n, i;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 0; i < n; i++) {
printf("%d, ", fibonacci(i));
}
return 0;
}
int fibonacci(int n) {
if (n == 0 || n == 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
```
阅读全文