C语言实现斐波那契数列
时间: 2023-08-31 08:42:45 浏览: 61
### 回答1:
今天是2020年11月2日。斐波那契数列是由0和1开始,之后的数字等于前两个数字之和。通过使用循环语句,可以使用C语言实现斐波那契数列:
int fibonacci(int n)
{
int a = 0, b = 1, c, i;
if( n == 0)
return a;
for (i = 2; i <= n; i++)
{
c = a + b;
a = b;
b = c;
}
return b;
}
### 回答2:
斐波那契数列是指每个数都是前两个数之和的数列。在C语言中,可以使用循环或者递归的方式实现斐波那契数列。
1. 使用循环实现斐波那契数列:
```c
#include <stdio.h>
int main()
{
int num;
printf("请输入斐波那契数列的长度:");
scanf("%d", &num);
int fib[num];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i < num; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
printf("斐波那契数列前 %d 项为:", num);
for (int i = 0; i < num; i++)
{
printf("%d ", fib[i]);
}
return 0;
}
```
2. 使用递归实现斐波那契数列:
```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;
printf("请输入斐波那契数列的长度:");
scanf("%d", &num);
printf("斐波那契数列前 %d 项为:", num);
for (int i = 0; i < num; i++)
{
printf("%d ", fibonacci(i));
}
return 0;
}
```
以上两种方法都可以实现斐波那契数列,循环方法比递归方法更高效,因为递归方法会重复计算一些数字。
### 回答3:
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;
printf("请输入要计算的斐波那契数列的项数:");
scanf("%d", &num);
printf("斐波那契数列的第 %d 项为 %d\n", num, fibonacci(num));
return 0;
}
```
2. 循环实现斐波那契数列:
```c
#include <stdio.h>
int fibonacci(int n) {
int a = 0, b = 1, result;
if (n == 0)
return a;
else if (n == 1)
return b;
else {
for (int i = 2; i <= n; i++) {
result = a + b;
a = b;
b = result;
}
return result;
}
}
int main() {
int num;
printf("请输入要计算的斐波那契数列的项数:");
scanf("%d", &num);
printf("斐波那契数列的第 %d 项为 %d\n", num, fibonacci(num));
return 0;
}
```
以上两种方法都可以根据输入的项数计算出相应的斐波那契数列的第n项,并打印出来。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)