c语言 用数组来求斐波那契数列问题前20项
时间: 2024-05-17 12:08:11 浏览: 173
计算斐波那契数列前20项
以下是两种C语言用数组来求斐波那契数列前20项的方法:
方法一:
```c
#include "stdio.h"
int main(){
int i,j;
int f[20] = {1,1};//赋值数列前两项
for(i = 2;i < 20; i++){
f[i] = f[i-1] + f[i-2]; //根据数列的定义,进行计算(N项的结果等于 (n-1)+(n-2))
}
for(j = 0 ; j < 20;j++){
//********5个一行**************//
if(j % 5 == 0) printf("\n");
printf("%d\t",f[j]);
}
return 0;
}
```
方法二:
```c
#include<stdio.h>
int main(){
int f[20] = {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; //等同于{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
for ( int i = 2; i < 20; i++ ) //计算f[2]-f[19]的值
f [ i ] = f [ i - 2 ] + f [ i - 1 ];
for ( int i = 0; i < 20; i++ ) {
//控制每行输出4个数后换行
if ( i%4==0 ) {
printf( "\n" );
}
printf( "%12d", f [ i ] );
}
printf( "\n" );
return 0;
}
```
阅读全文