如何用c语言输出斐波那契数列
时间: 2023-10-18 11:20:23 浏览: 94
可以使用循环或递归的方式来输出斐波那契数列。以下是使用循环的示例代码:
```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;
}
```
运行结果:
```
Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
```
在这个示例中,我们使用 `t1` 和 `t2` 来存储斐波那契序列的前两个数字,然后使用循环来计算每个后续数字,并将其打印到屏幕上。
如果你想使用递归来输出斐波那契数列,可以使用以下代码:
```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));
}
}
```
运行结果:
```
Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
```
在这个示例中,我们定义了一个名为 `fibonacci` 的函数来计算斐波那契数列中的每个数字。如果 `n` 的值为0或1,则直接返回 `n`。如果 `n` 的值大于1,则使用递归来计算前两个数字的和,并返回结果。在 `main` 函数中,我们使用循环来输出斐波那契数列中的每个数字。
阅读全文
相关推荐
![](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)
![](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/20241231044930.png)