我有两个类,Progression和FibonacciProgression,但是FibonacciProgression在4和6上调用print方法时打印出一些意想不到的结果,如下所示。谁能解释为什么会这样?
public class Progression {
protected long first;
protected long cur;
Progression() {
cur = first = 0;
}
protected long firstValue() {
cur = first;
return cur;
}
protected long nextValue() {
return ++cur;
}
public void printProgression(int n) {
System.out.print(firstValue());
for (int i = 2; i <= n; i++) {
System.out.print(" " + nextValue());
}
System.out.println();
}
public static void main (String[] args) {
Progression prog = new Progression();
System.out.println("Default Progression: ");
prog.printProgression(10);
}
}
和..
public class FibonacciProgression extends Progression {
protected long prev;
FibonacciProgression(long value1, long value2) {
first = value1;
prev = value2 - value1;
}
FibonacciProgression() {
this(0,1);
}
protected long nextValue() {
long temp = prev;
prev = cur;
cur += temp;
return cur;
}
public static void main (String[] args) {
Progression fibProg = new FibonacciProgression(2,5);
System.out.println("Default Progression: ");
fibProg.printProgression(4);
fibProg.printProgression(6);
}
}
答案 0 :(得分:2)
当您使用参数6第二次调用printProgression
时,prev
的值不会重置为其初始值。 prev
仍包含上次调用的值7。您需要在value2
中保存FibonacciProgression
,并在调用prev
firstValue
时重置FibonacciProgression
。像这样:
protected long firstValue() {
prev = val2 - first; // val2 is value2 passed in constructor
return super.firstValue();
}
答案 1 :(得分:1)
您的printProgression“销毁”了上一个值。 要轻松看到它,请将主切换到:
public static void main(String[] args) {
Progression fibProg = new FibonacciProgression(2, 5);
System.out.println("Default Progression: ");
fibProg.printProgression(4);
fibProg = new FibonacciProgression(2, 5);
fibProg.printProgression(6);
}