【问题标题】:Fibonacci Range in JavaJava中的斐波那契范围
【发布时间】:2014-10-20 17:54:39
【问题描述】:

大家好,我想创建一个 java 程序来查找一系列数字内的斐波那契数列。现在我想输入另一个输入,以便我可以获得斐波那契数的输入值

例如,如果最小值为 10,最大值为 150,则结果将为 13 21 35 55 89 144,但在第三个输入中,如果值为 2,我希望仅给我 13 和 21 作为结果。

有什么帮助吗??

我的代码是:

public void actionPerformed(ActionEvent e) {
                String x = t1.getText();
                String y = t3.getText();
                String o = t4.getText();
                if (x.isEmpty()) {
                    JOptionPane.showMessageDialog(TestFibMethodRange.this, "This field cannot be empty", "Required Field", JOptionPane.ERROR_MESSAGE);
                } else if (y.isEmpty()) {
                    JOptionPane.showMessageDialog(TestFibMethodRange.this, "This field cannot be empty", "Required Field", JOptionPane.ERROR_MESSAGE);
                } else if (o.isEmpty()) {
                    JOptionPane.showMessageDialog(TestFibMethodRange.this, "This field cannot be empty", "Required Field", JOptionPane.ERROR_MESSAGE);
                } else {
                    if (isInteger(x) && isInteger(y) && isInteger(o)) {
                        int min = Integer.valueOf(x);
                        int max = Integer.valueOf(y);
                        int nSequence = Integer.valueOf(o);
                        for (int i = min; i <= nSequence; i++) {
                            if (x3 <= max) {
                                if (x3 >= min) {
                                    t2.setText(t2.getText() + " " + x3);
                                }
                                x1 = x2;
                                x2 = x3;
                                x3 = x1 + x2;
                            }
                        }
                    }
                }

            }

【问题讨论】:

  • 使用Binet's formula,希望对您有所帮助。
  • 我不知道如何使用它。你能帮忙吗??
  • 现在我想输入另一个输入,以便获得斐波那契数的输入值。这句话没看懂……
  • @CommuSoft :他的意思是 javac - MyClass 10 150 2 表示他想打印 10 到 150 之间的前 2 个斐波那契数。
  • @FahimParkar:谢谢,一分钟后发现(见下面的答案)。

标签: java fibonacci


【解决方案1】:

您的程序可能无法正常运行,因为o 是预期项目的数量,但您首先需要计算“偏移量”,因此已经计算了一些太低的数字。换句话说,i 在发射实际开始时已经有一个大于0 的值。

更好的方法:

int xa = 0, xb = 0, xc = 1;
while(xc < min) {
    xa = xb;
    xb = xc;
    xc += xa;
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i < nSequence && xc <= max; i++) {
    sb.append(xc);
    sb.append(' ');
    xa = xb;
    xb = xc;
    xc += xa;
}
t2.setText(sb.toString());

Demo.

【讨论】:

  • @FahimParkar:需要一个人发送数据到recruitcoders.com。换句话说,第三方请求/隐私泄露。
  • @FahimParkar:好吧,我没有设置文本字段,而是写信给stdout,因为没有图形外壳。
猜你喜欢
  • 1970-01-01
  • 2015-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-09
  • 1970-01-01
  • 2012-12-29
  • 1970-01-01
相关资源
最近更新 更多