好的,所以我一直在制作斐波那契系列节目,例如(0 1 1 2 3 5 8 13 21 ..)。我的逻辑很好,但是当我从for()循环到外面时,存在可变状态问题。 如何保持我的" firstNumber"状态如何? 我不知道为什么它打印价值直到19,虽然我给输入值10
public class Fibonacci {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number: ");
int input = scan.nextInt();
FibonacciFunction(input);
}
public static int FibonacciFunction(int x) {
int firstNumber = 0;
int i;
for(i =1; i <= x; i++) {
int numbers = firstNumber + i;
System.out.println(numbers);
firstNumber = i; //Keep this state as it is so that when loop run for the second time "firstNumber" should be 1 not 0 again
}
return firstNumber;
}
}
输出 输入数字: 10 1 3 五 7 9 11 13 15 17 19
答案 0 :(得分:2)
您的逻辑不正确:您正在将i
循环的迭代器值for
添加到最后一个数字,但您需要将倒数第二个数字添加到最后一个数字中Fibonacci序列。因此,您的firstNumber
变量不应该保持在1
或0
的“状态”,但随着循环的继续,它应随Fibonacci序列一起增长。
public static int FibonacciFunction(int x) {
if(x <= 0) return 0;
int firstNumber = 0, secondNumber = 1;
for(int i = 0; i < x; i++) {
int numbers = firstNumber + secondNumber;
firstNumber = secondNumber;
secondNumber = numbers;
System.out.println(numbers);
}
return firstNumber;
}
它的打印值直到19,因为函数的参数是您希望打印的Fibonacci值的数量,而不是最大的Fibonacci数。
答案 1 :(得分:-1)
To solve your error, you are saying that you want firstNumber to not be 0 when it comes out of the for loop. It is impossible for firstNumber to be 0 at the end of the for loop unless the for loop didn't happen. When you say it is coming back 0 that means the forloop is not going, in which case it returns the original value of firstNumber which is 0. This means the value x is incorrect, or the way you read it in is incorrect.
Trying putting in a S.O.P statement after the firstNumber =i;
to see what the value actually is:
public static int FibonacciFunction(int x) {
int firstNumber = 0;
int i;
for(i =1; i <= x; i++) {
int numbers = firstNumber + i;
System.out.println(numbers);
firstNumber = i;
System.out.print(" First Number Value: "+ firstNumber);
}
return firstNumber;
}