如何在Java中创建斐波那契数列
我数学真的很差。我的意思是,我真的很差。 我正在尝试制作一个简单的斐波那契数列类,用于我将要使用的算法。我看过一个Python的例子,大概是这样的:
a = 0
b = 1
while b < 10:
print b
a, b = b, b+a
问题是,我在其他语言中根本无法做到这一点。我想在Java中实现它,因为我可以从那里把它翻译成我使用的其他语言。这是我的大致想法:
public class FibonacciAlgorithm {
private Integer a = 0;
private Integer b = 1;
public FibonacciAlgorithm() {
}
public Integer increment() {
a = b;
b = a + b;
return value;
}
public Integer getValue() {
return b;
}
}
结果我得到的只是倍增,这我用乘法就能做到 :( 有没有人能帮帮我?数学真让我头疼。
10 个回答
2
你需要先把 a 或 b 的值存储到一个临时变量中;
public Integer increment()
{
int temp = a;
a = b;
b = temp + b;
return value;
}
4
这一行
a, b = b, b+a
不太好翻译。大概是这个意思。你可以把它简化一下。这是字面上的意思。
t1 = b
t2 = b+a
a = t1
b = t2
7
我会这样做:
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public int increment() {
int temp = b;
b = a + b;
a = temp;
return value;
}
public int getValue() {
return b;
}
}
这样做能让你的代码尽量接近原来的Java代码。
[编辑说明:Integers
已经被ints
替换了。这里没有必要使用Integers
。]