C语言输出Fibonacci数列前40项
时间: 2024-06-13 16:09:10 浏览: 13
以下是C语言输出Fibonacci数列前40项的两种方法:
1.使用循环和两个变量计算并输出Fibonacci数列前40项:
```c
#include <stdio.h>
int main() {
long int f1, f2, i;
f1 = 1;
f2 = 1;
for (i = 1; i <= 40; i++) {
printf("%12ld%12ld", f1, f2);
f1 = f1 + f2;
f2 = f2 + f1;
if (i % 2 == 0) {
printf("\n");
}
}
return 0;
}
```
2.使用数组实现斐波那契数列,并且可以加上想要输出的项:
```c
#include <stdio.h>
#define N 10000 //数组中容纳的项数
int main() {
long int a[N] = {1, 1};
int n;
printf("输入想求的项数:");
scanf("%d", &n);
for (int i = 2; i < n; i++) {
a[i] = a[i - 1] + a[i - 2];
}
printf("%ld", a[n - 1]);
return 0;
}
```
相关问题
c语言输出fibonacci数列的前40项
好的,这是一个编程问题,可以回答。以下是一段用C语言输出Fibonacci数列的前40项的代码:
```
#include <stdio.h>
int main() {
int i, n = 40, t1 = 0, t2 = 1, nextTerm;
printf("Fibonacci Series (First %d Terms):\n", n);
for (i = 1; i <= n; i++) {
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
```
这段代码通过循环计算Fibonacci数列的每一项,并输出前40项。
c语言 输出斐波那契数列的前 21 项
好的,下面是C语言输出斐波那契数列的前21项的代码:
```c
#include <stdio.h>
int main()
{
int n = 21, first = 0, second = 1, next, c;
printf("前 %d 项斐波那契数列:\n", n);
for (c = 0; c < n; c++)
{
if (c <= 1)
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n", next);
}
return 0;
}
```
输出结果如下:
```
前 21 项斐波那契数列:
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)