英文:
how do I create the number entered into 6 consecutive calls in java?
问题
以下是您要翻译的代码部分:
import java.util.Date;
import java.util.Scanner;
class Main
{
public static int count = 0;
public static int fibonacci(int a)
{
count +=1;
if (a<=1)
{
return a;
}
return fibonacci(a-1)+fibonacci(a-2);
}
public static void main(String args[])
{
int n =6;
for (int i=1; i<= n; ++i){
long start=new Date().getTime();
Scanner s=new Scanner(System.in);
System.out.println("Enter a number: ");
int a= s.nextInt();
System.out.println("This Fibonacci number =" +fibonacci(a));
long end=new Date().getTime();
System.out.println("seconds used for this calculation ="+((end-start)/1000));
}
}
}
希望这有助于您解决实现连续调用的问题。
英文:
I am having trouble implementing a consecutive call here. For example I want the user to only enter a number once, say 40.. and have 6 consecutive calls.
import java.util.Date;
import java.util.Scanner;
class Main
{
public static int count = 0;
public static int fibonacci(int a)
{
count +=1;
if (a<=1)
{
return a;
}
return fibonacci(a-1)+fibonacci(a-2);
}
public static void main(String args[])
{
int n =6;
for (int i=1; i<= n; ++i){
long start=new Date().getTime();
Scanner s=new Scanner(System.in);
System.out.println("Enter a number: ");
int a= s.nextInt();
System.out.println("This Fibonacci number =" +fibonacci(a));
long end=new Date().getTime();
System.out.println("seconds used for this calculation ="+((end-start)/1000));
}
}
}
this is what I have so far.
答案1
得分: 1
将你的Scanner和int a移到for循环外部。目前,Scanner被连续运行了6次。
英文:
Move your Scanner and int a outside the for loop. Currently, the Scanner is being run 6 consecutive times.
答案2
得分: 1
这将在括号内运行所有内容6次。如果您只想运行第二部分6次,请将其限制在其中。
此外,您从未定义了"start",所以您的计时代码根本不会起作用。
public static void main(String args[])
{
int n = 6;
long start = new Date().getTime();
Scanner s = new Scanner(System.in);
System.out.println("输入一个数字:");
int a = s.nextInt();
for (int i = 1; i <= n; ++i){
long start = new Date().getTime();
System.out.println("这个斐波那契数 = " + fibonacci(a));
long end = new Date().getTime();
System.out.println("用于这个计算的秒数 = " + ((end - start) / 1000));
}
}
英文:
This will run everything inside the brackets 6 times. If you want only the second part to be run 6 times, confine it to that.
Also you never defined start, so your timing code won't work at all.
public static void main(String args[])
{
int n =6;
long start=new Date().getTime();
Scanner s=new Scanner(System.in);
System.out.println("Enter a number: ");
int a= s.nextInt();
for (int i=1; i<= n; ++i){
long start=new Date().getTime();
System.out.println("This Fibonacci number =" +fibonacci(a));
long end=new Date().getTime();
System.out.println("seconds used for this calculation ="+((end-start)/1000));
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论