java用递归编程求斐波那契数列第n项

如题所述

public class Fibonacci {
public static void main(String args[]){
int n,fn;//n为第n项,fn为第n项的值
java.util.Scanner s = new Scanner(System.in);
n=s.nextInt();
fn=function(n);
System.out.println("斐波那契数列第"+n+"项为:"+fn);
}

public static int function(int n){
if(n==1 || n==2) return 1;
return function(n-1)+function(n-2);
}

}
希望能帮到你,其实和c语言是一样一样的。。
温馨提示:内容为网友见解,仅供参考
第1个回答  2012-11-11
套数学里的就是了 f(0) = 1, f(1) = 1, f(2) = 2, ...

int fib(int i){
if( i < 2 ) return 1; // 递归结束的条件

return f(i -1) + f(i-2);

}本回答被网友采纳
第2个回答  2012-11-13
import java.io.*;
public class Zhidao1 {
public static void main(String[] args) {
Zhidao1 z1=new Zhidao1();
int n;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入要求的数是第几个数:");
try {
String str=br.readLine();
n=Integer.parseInt(str);
System.out.println("第"+n+"个斐波那契数是:\n"+z1.getFib(n));
} catch (Exception e) {
e.printStackTrace();
}
}
public long getFib(int n)
{
long fn;
if(n==1||n==2)
fn=1;
else
fn=getFib(n-1)+getFib(n-2);
return fn;
}
}
第3个回答  2018-09-16
这样做,从内存上来说,深层次的递归容易造成栈溢出,我推荐这种

public static void main(String[] args) {
int i=1;
int t=1;
for(int s=0;s<10;s++){
System.out.println(i);
if(s>0){
i += t;
t = i-t;
}
}
}
第4个回答  2012-11-11
 public class Test {
  public static void main(String args[]) {
  int x1 = 1;
  int sum = 0;
  int n = 7;
  for (int i = 1; i <= n; i++) {
  x1 = func(i);
  sum = sum + x1;
  }
  System.out.println("sum=" + sum);
  }
  public static int func(int x) {
if (x > 2)
//返回前两个数的和
  return (func(x - 1) + func(x - 2));//返回前两个数的和
  else
  return 1;
  }
  }
相似回答