如何在Java中创建Fibonacci序列

前端之家收集整理的这篇文章主要介绍了如何在Java中创建Fibonacci序列前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我真的很厌倦数学.我的意思是,我真的很喜欢数学.
我正在尝试为我将使用的算法制作一个简单的斐波那契序列类.我见过python示例,看起来像这样:

@H_404_6@a = 0 b = 1 while b < 10: print b a,b = b,b+a

问题是我无法用任何其他语言实现这项工作.我想让它在Java中工作,因为我几乎可以将它翻译成我在那里使用的其他语言.这是一般的想法:

@H_404_6@ 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; } }

我最终得到的就是加倍,我可以用乘法来做:(
谁能帮我吗?数学让我感到高兴.

最佳答案
我这样做:

@H_404_6@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.]

猜你在找的Java相关文章