gpt4 book ai didi

java - 如何在 Java 中创建斐波那契数列

转载 作者:太空狗 更新时间:2023-10-30 00:30:48 24 4
gpt4 key购买 nike

我的数学真的很烂。我的意思是,我真的很不擅长数学。我正在尝试为我将要使用的算法制作一个简单的斐波那契数列类。我看过看起来像这样的 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;
}
}

我最终得到的结果是加倍,我可以用乘法来做:(谁能帮我吗?数学打败了我。

最佳答案

我会这样做:

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。]

关于java - 如何在 Java 中创建斐波那契数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1045151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com