打印斐波那契数列的结果 [英] printing the results of a fibonacci series
本文介绍了打印斐波那契数列的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道斐波那契数列的编码是:
I know that the coding for the Fibonacci series is:
int fib(int n)
{
if (n==0 || n==1) return n;
else return fib(n-1)+fib(n-2);
}
我想知道是否有一种方法可以使用前面提到的代码来打印系列的先前结果,但是没有使用void函数(仅像该系列的打印机那样)或为每个函数调用fibonacci函数计算
I was wondering if there is a way, using the aforementioned code, to print the previous results of the series, but neither using a void function (that acts only like a printer of the series) or calling the fibonacci funcion for each calculation
我不想这样做
for (int i=0;i<4;i++){
System.out.prinntln(fib(i));
}
Intead我只想调用一次函数,就像这样:
Intead I want to only call the function once, like this:
fib(4);
打印结果是:
0,1,1,2,3
0,1,1,2,3
当然使用递归
有什么主意吗?谢谢
推荐答案
package Practice;
public class Fabonacci {
public static void main(String[] args)
{
int a,b,c;
a=0;
b=1;
c=2;
for(int i=1; i<=10; i++)
{
c=a+b;
System.out.println(a);
a=b;
b=c;
}
}
}
这将输出为:
0 1 1 2 3 5 8 13 21 34
这篇关于打印斐波那契数列的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文