java用遞歸編程求斐波那契數列第n項
題目:
java用遞歸編程求斐波那契數列第n項
解答:
public class Fibonacci {
\x09public 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);
\x09}
\x09public static int function(int n){
if(n==1 || n==2) return 1;
return function(n-1)+function(n-2);
\x09}
}
希望能幫到你,其實和c語言是一樣一樣的.
添加新評論