Based on the CC150 solution and introduction to Java Programming Summary:
There are two ways of using recursion and iteration
The code provided by CC150 is relatively concise, but some details need to be analyzed.
Now run the code directly, enter the value of n (where number is substituted to avoid confusion with N in the method), and you can derive Fibonacci numbers.
The code is as follows:
/*CC150 8.1 Write a method to generate the nth Fibonacci number Author:mengyang Rao Note:use the methods , iteration and recursion date:2015-02-25 23:56:00*/ImportJava.util.Scanner; Public classTestfibonacci { Public Static voidMain (string[] args) {Scanner input=NewScanner (system.in); System.out.print ("Please enter N:"); intNumber =Input.nextint (); System.out.println ("The iteration number is:" + Fibonacci (number) + "\ n value is:" +Number ); System.out.println ("The recursion number is:" + fibo (number) + "\ n value is:" +Number ); }//version:recursion Public Static LongFiboLongN) {if(n = = 0) return0; Else if(n = = 1) return1; Else if(N > 1) returnFibo (n-1) + Fibo (n-2); Else return-1;}//version:iteration Public Static LongFibonacciLongN) {intA = 0, B = 1; if(N < 0) return-1; Else if(n = = 0) return0; for(inti = 3; I <= N; i++) { intc = A +b; A=b; b=C; } returnb; }}
(Fibonacci Summary) Write a method to generate the nth Fibonacci number (CC150 8.1)