用C语言实现用循环和递归算法求斐波那契额数列的前 10 项
时间: 2023-12-10 14:39:06 浏览: 82
循环实现:
```c
#include <stdio.h>
int main() {
int n = 10;
int i, t1 = 0, t2 = 1, nextTerm;
printf("Fibonacci Series: ");
for (i = 1; i <= n; ++i) {
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
```
递归实现:
```c
#include <stdio.h>
int fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n-1) + fibonacci(n-2);
}
}
int main() {
int n = 10;
int i;
printf("Fibonacci Series: ");
for (i = 0; i < n; ++i) {
printf("%d, ", fibonacci(i));
}
return 0;
}
```
相关问题
C语言用循环和递归算法求斐波那契额数列的前 10 项
用循环实现斐波那契数列:
```c
#include <stdio.h>
int main() {
int i, n, t1 = 0, t2 = 1, nextTerm;
printf("斐波那契数列前10项:\n");
for (i = 1; i <= 10; i++) {
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
```
用递归实现斐波那契数列:
```c
#include <stdio.h>
int fibonacci(int n) {
if (n == 0) {
return 0;
}
else if (n == 1) {
return 1;
}
else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
int main() {
int n = 10, i;
printf("斐波那契数列前10项:\n");
for (i = 0; i < n; i++) {
printf("%d, ", fibonacci(i));
}
return 0;
}
```
用循环和递归算法求斐波那契额数列的前 10 项。帮我写个c语言代码来实现
好的,以下是使用循环和递归算法求斐波那契数列的前 10 项的 C 语言代码:
使用循环:
```c
#include <stdio.h>
int main() {
int i, n = 10;
int fib[n];
fib[0] = 0;
fib[1] = 1;
for (i = 2; i < n; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
printf("斐波那契数列的前 %d 项为:\n", n);
for (i = 0; i < n; i++) {
printf("%d ", fib[i]);
}
return 0;
}
```
使用递归:
```c
#include <stdio.h>
int fib(int n) {
if (n <= 1) {
return n;
}
return fib(n-1) + fib(n-2);
}
int main() {
int i, n = 10;
printf("斐波那契数列的前 %d 项为:\n", n);
for (i = 0; i < n; i++) {
printf("%d ", fib(i));
}
return 0;
}
```
希望能帮助到你!