C语言递归实现输出1000以内的斐波那契数列
时间: 2023-05-23 18:01:52 浏览: 58
以下是C语言递归实现输出1000以内的斐波那契数列的代码:
```c
#include <stdio.h>
int fib(int n)
{
if (n <= 1)
return n;
return fib(n-1) + fib(n-2);
}
int main()
{
int i;
for (i=0; i<1000; i++) {
printf("%d ", fib(i));
}
return 0;
}
```
你可以运行这段代码,它将输出1000以内的斐波那契数列。
相关问题
C语言递归实现输出1000以前的斐波那契数列
以下是 C 语言递归实现输出1000以前的斐波那契数列的代码:
```C
#include <stdio.h>
int fibonacci(int n)
{
if (n == 0 || n == 1) { // 最基本的情况
return n;
} else {
return fibonacci(n-1) + fibonacci(n-2); // 递归调用
}
}
int main()
{
int i;
for (i = 0; i < 1000; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}
```
注意:该代码只是为了演示递归实现斐波那契数列的方法,并没有进行任何优化,对于比较大的 n 值,性能会非常低下。
c语言递归实现斐波那契数列代码
下面是C语言递归实现斐波那契数列的代码:
```c
#include <stdio.h>
int fun(int n) {
if(n == 1 || n == 2) {
return 1;
} else {
return fun(n-1) + fun(n-2);
}
}
int main() {
int i, n;
printf("请输入你要打印的斐波那契数列项数:\n");
scanf("%d", &n);
printf("斐波那契数列:");
for(i = 1; i <= n; i++) {
printf("%d ", fun(i));
}
return 0;
}
```
该代码通过递归的方式实现了斐波那契数列的求解,其中fun函数用于递归求解第n项斐波那契数列的值,main函数中通过循环调用fun函数来打印出前n项斐波那契数列的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)