该程序本身运行良好.输入的每个值都将返回正确的对应斐波那契数.我还需要定时执行递归函数和使用循环的函数.当我运行程序时,它只是返回用户实际输入其输入所花费的时间,而不是运行函数所花费的时间.我已经尝试过移动计时器,但我一直得到相同的结果.我想返回递归计算斐波那契数的实际时间,以及使用循环计算斐波那契数的时间.
import java.util.Scanner;
public class FibNumbers {
public static void main(String[] args) {
int f;
int l;
long num1;
long num2;
int choice;
long t1 = System.currentTimeMillis();
Scanner sc = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
System.out.println("For recursion press 1 %n for loop press 2" );
choice = keyboard.nextInt();
if(choice == 1) {
System.out.println("Please enter a value for n");
f = Integer.parseInt(sc.nextLine());
System.out.println("The Fibonacci number is " + fibonacciR(f) + " using recursion");
}
else {
System.out.println("Please enter a value for n");
l = Integer.parseInt(sc.nextLine());
System.out.println("The Fibonacci number is " + fibonacciL(l) + " using a for loop");
}
long t2 = System.currentTimeMillis();
System.out.println("The elapsed time is " + (t2 - t1) / 1000 + " seconds.");
}
public static long fibonacciR(long f) {
if(f == 0) {
return 0;
}
else if(f == 1) {
return 1;
}
else {
return fibonacciR(f-1) + fibonacciR(f-2);
}
}
public static long fibonacciL(long l) {
long num1 = 0;
long num2 = 1;
long total = l;
long sumOfTwo;
for(int i = 0; i < total; i++) {
sumOfTwo = num1 + num2;
num1 = num2;
num2 = sumOfTwo;
}
return num1;
}
}
解决方法:
使用System.nanoTime();纳秒.
如果(t2-t1)小于1000,则除以1000将得到0,因为您使用的时间很长,可以将其强制转换为float / double,然后进行除法.
可能是这样的:
import java.util.Scanner;
public class FibNumbers {
public static void main(String[] args) {
int f;
int l;
long num1;
long num2;
int choice;
long t1 = 0, t2 = 0;
Scanner sc = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
System.out.println("For recursion press 1 %n for loop press 2" );
choice = keyboard.nextInt();
if(choice == 1) {
System.out.println("Please enter a value for n");
f = Integer.parseInt(sc.nextLine());
t1 = System.nanoTime();
System.out.println("The Fibonacci number is " + fibonacciR(f) + " using recursion");
t2 = System.nanoTime();
}
else {
System.out.println("Please enter a value for n");
l = Integer.parseInt(sc.nextLine());
t1 = System.currentTimeMillis();
System.out.println("The Fibonacci number is " + fibonacciL(l) + " using a for loop");
t2 = System.nanoTime();
}
System.out.println("The elapsed time is " + (t2 - t1) + " nano seconds.");
}
public static long fibonacciR(long f) {
if(f == 0) {
return 0;
}
else if(f == 1) {
return 1;
}
else {
return fibonacciR(f-1) + fibonacciR(f-2);
}
}
public static long fibonacciL(long l) {
long num1 = 0;
long num2 = 1;
long total = l;
long sumOfTwo;
for(int i = 0; i < total; i++) {
sumOfTwo = num1 + num2;
num1 = num2;
num2 = sumOfTwo;
}
return num1;
}
}