方法一for循环
publicclassFeiBoMethod{
定义三个变量方法
publicstaticvoidmain(String[]args){
inta=1,b=1,c=0;
System.out.println("斐波那契数列前20项为:");
System.out.print(a+"\t"+b+"\t");
因为前面还有两个1、1所以i<=18
for(inti=1;i<=18;i++){
c=a+b;
a=b;
b=c;
System.out.print(c+"\t");
if((i+2)%4==0)
System.out.println();
}
}
}
方法2使用数组的方式实现
publicclassFeiBoMethod{
定义数组方法
publicstaticvoidmain(String[]args){
intarr[]=newint[20];
arr[0]=arr[1]=1;
for(inti=2;i<arr.length;i++){
arr[i]=arr[i-1]+arr[i-2];
}
System.out.println("斐波那契数列的前20项如下所示:");
for(inti=0;i<arr.length;i++){
if(i%4==0)
System.out.println();
System.out.print(arr[i]+"\t");
}
}
}
扩展资料:
递归实现
publicclassFeiBoMethod{
使用递归方法
privatestaticintgetSum(intnum){
if(num==1||num==2)
return1;
else
returngetSum(num-1)+getFibo(num-2);
}
publicstaticvoidmain(String[]args){
System.out.println("斐波那契数列的前20项为:");
for(inti=1;i<=20;i++){
System.out.print(getSum(i)+"\t");
if(i%4==0)
System.out.println();
}
}
}
#include <stdio.h>
int main(void) {
int n; // 输入一个数字 N
int i; // 第 i 个将要输出的斐波那契数
int current; // 第 i 个斐波那契数的值
int next; // 下一个(i+1)斐波那契数的值
int twoaway; // 下下个(i+2)斐波那契数的值
printf("您需要斐波那契数列的前几项?请输入: ");
scanf("%d", &n);
if (n<=0)
printf("请输入正整数!\n");
else {
printf("前%d项斐波那契数列为:\n",n);
next = current = 1;
for (i=1; i<=n; i++) {
printf("%d\t",current);
if (i%4==0) printf("\n");// 控制每输出4个数换一行
twoaway = current+next;
current = next;
next = twoaway;
}
}
}
执行结果
输入:20,即题主希望输出前20项斐波那契数列。这里注意,斐波那契数列“第0项”为“0”,这里以第1项开始。
2013-06-04
#include <malloc.h>int fibonacci(int n);
void createFibArray(int *buf, int size);
int printArray(FILE *fp, const int *buf, int size, int colum, const char *columseperator, const char *rowseperator);int main()
{
const int SIZE = 20;
int *fibArray = (int *)malloc(sizeof(int) * SIZE);
if (fibArray == NULL)
{
return -1;
}
createFibArray(fibArray, SIZE);
printArray(stdout, fibArray, SIZE, 4, "\t", "\n");
return 0;
}int fibonacci(int n)
{
if (n == 0)
{
return 0;
}
if (n == 1)
{
return 1;
}
int a1 = 0, a2=1;
int i = 0;
for (i = 0; i<n-1; i++)
{
a2 = a1 + a2;
a1 = a2 - a1;
}
return a2;
}void createFibArray(int *buf, int size)
{
int i = 0;
for (i = 0; i < size; i++)
{
buf[i] = fibonacci(i);
}
}int printArray(FILE *fp, const int *buf, int size, int colum, const char *columseperator, const char *rowseperator)
{
int i = 0;
int count = 0;
for (i = 0; i<size; i++)
{
count += fprintf(fp,"%d",buf[i]);
if (i == size -1)
{
continue;
}
if ((i+1)%colum == 0)
{
count += fprintf(fp, rowseperator);
}
else
{
count += fprintf(fp, columseperator);
}
}
count +=fprintf(fp,"\n");
return count;
}
2013-06-04
int main()
{
int f1=1,f2=1;
int i;
for(i=1;i<=20;++i)
{
printf("%-12d%-12d",f1,f2);
if(i%2==0)
printf("\n");
f1=f1+f2;
f2=f1+f2;
}
printf("\n");
return 0;
}