c++输出fibonacci数列前20项每行输出5个代码
时间: 2024-05-25 20:18:48 浏览: 11
#include <stdio.h>
int main() {
int n = 20;
int a = 0, b = 1;
int i, count = 0;
for (i = 1; i <= n; i++) {
printf("%d ", a);
count++;
if (count == 5) {
printf("\n");
count = 0;
}
int temp = b;
b = a + b;
a = temp;
}
return 0;
}
相关问题
用c++语言输出斐波那契数列前20项并且每行输出5
以下是用C++语言输出斐波那契数列前20项并且每行输出5的代码:
```c++
#include <iostream>
using namespace std;
int main()
{
int fib[20];
fib[0] = 0;
fib[1] = 1;
cout << "斐波那契数列前20项为:" << endl;
for (int i = 2; i < 20; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for (int i = 0; i < 20; i++)
{
cout << fib[i] << " ";
if ((i+1) % 5 == 0)
{
cout << endl;
}
}
return 0;
}
```
输出结果为:
```
斐波那契数列前20项为:
0 1 1 2 3
5 8 13 21 34
55 89 144 233 377
610 987 1597 2584 4181
```
用c++递归求出斐波那契数列前n项,且每行输出5个数
好的,这个问题我可以回答。下面是完整的 C 代码实现:
```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, i;
printf("请输入要求的斐波那契数列前n项: ");
scanf("%d", &n);
printf("斐波那契数列前%d项为:\n", n);
for (i = 0; i < n; i++)
{
printf("%12d", fibonacci(i));
if ((i+1) % 5 == 0)
printf("\n");
}
return 0;
}
```
这个程序使用递归方式计算斐波那契数列前n项,每行输出5个数。注意,当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_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)