作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
程序本身运行良好。我输入的每个值都会返回正确的相应斐波那契数。我还需要计算递归函数和使用循环的函数的执行时间。当我运行程序时,它只返回用户实际输入他们的输入所花费的时间,而不是运行函数所花费的时间。我试过移动计时器,但我一直得到相同的结果。我想返回递归计算斐波那契数实际花费的时间以及使用循环计算斐波那契数需要多长时间。
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,因为您使用的是 long,您可以转换为 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;
}
}
关于Java 斐波那契数列计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48604755/
我是一名优秀的程序员,十分优秀!