【发布时间】:2018-08-01 13:24:22
【问题描述】:
我试图让它打印出代码的递归部分,就像它打印出迭代一样。 迭代中的斐波那契数列
1
1
2
3
5
8
13
21
34
斐波那契数列在 9 处的结尾是 34 时间:1。就像这样,但是每次我尝试循环打印时,我都会得到一些奇怪的答案,不确定要添加到方法中的内容。
import java.util.Scanner;
public class fibonacciRecursive {
public static void main(String[] args) {
/*
* Dustin Willingham
* Class: CSCI 1302 Mon-Wed Cartersville
*Lets user enter the last number of a fibonacci sequence
*then it takes the number and runs the fibonacci sequence in recursive and iteration method
*It outputs the answer for both and the time
*/
Scanner in = new Scanner(System.in);
System.out.println("Enter the number you want the Fibonacci sequence to go to:");
int fibNumb = in.nextInt();
//Print and timing for the Fibonacci sequence with the Recursive method
System.out.println("Fibonacci sequence in recursion");
//start of the timer
long start = System.currentTimeMillis();
System.out.println("The ending of the fibonacci sequence at " + fibNumb + " is " + fibonacciRec(fibNumb));
System.out.print("Time : ");
//print out the timer
System.out.println(System.currentTimeMillis() - start);
//Print and timing for the Fibonacci sequence with the Iteration method
System.out.println("\n" + "Fibonacci sequence in iteration");
start = System.currentTimeMillis();
System.out.println("The ending of the fibonacci sequence at " + fibNumb + " is " + fiboacciIte(fibNumb));
System.out.print("Time : ");
System.out.print(System.currentTimeMillis() - start);
in.close();
}
// Recursive method for the Fibonacci sequence
public static int fibonacciRec(int fibNumb) {
if ((fibNumb == 1) || (fibNumb == 0)) {
return fibNumb;
}
int answer = fibonacciRec(fibNumb - 1) + fibonacciRec(fibNumb - 2);
return answer;
}
//Iteration method for the Fibonacci sequence
static int fiboacciIte(int fibNumb) {
int a = 0, b = 1, c = 1;
for (int d = 0; d < fibNumb; d++) {
a = b;
b = c;
System.out.println(a);
c = a + b;
}
return a;
}
}
【问题讨论】: