我的作业有困难..."编写一个程序,询问用户两个数字:下部和上部。你的程序应该打印从下到上的所有Fibonacci数字以及Fibonacci系列中所有偶数的总和。"我不知道如何获得两个输入之间的数字。现在它只是将数字从零到......?
这是我到目前为止所做的:
public static void main(String[] args)
{
Scanner scr = new Scanner(System.in);
System.out.println ("Enter lower bound:");
int lower = Integer.parseInt(scr.nextLine());
System.out.println ("Enter upper bound:");
int upper = Integer.parseInt(scr.nextLine());
int fiboCounter = 1;
int first = 0;
int second = 1;
int fibo = 0;
int oddTotal = 1;
System.out.println("The fibonacci numbers between ");
while(fiboCounter < upper)
{
fibo= first + second;
first = second;
second = fibo;
if(fibo % 2 == 0)
oddTotal = oddTotal + fibo;
System.out.print(" "+ fibo+ " ");
fiboCounter++;
}
System.out.println();
System.out.println("Total of even Fibos: "+ oddTotal);
}
答案 0 :(得分:0)
您只需检查计算出的数字是否足够大:
public static void main(String[] args) {
Scanner scr = new Scanner(System.in);
System.out.println ("Enter lower bound:");
int lower = Integer.parseInt(scr.nextLine());
System.out.println ("Enter upper bound:");
int upper = Integer.parseInt(scr.nextLine());
// This is how you can initialize multiple variables of the same type with the same value.
int fiboCounter, second, oddTotal = 1;
int first, fibo = 0;
System.out.println("The fibonacci numbers between ");
while( fiboCounter < upper ) {
fibo= first + second;
first= second;
second=fibo;
if(fibo%2==0) oddTotal=oddTotal+fibo;
// Just check if its high enough
if(fibo > lower ) {
System.out.print(" "+ fibo + " ");
}
fiboCounter++;
}
System.out.println("\nTotal of even Fibos: "+ oddTotal);
// The \n is just the same as System.out.println()
// You probably want to close the scanner afterwards
scanner.close();
}
我修改了一些代码并使其更具可读性。