大家好,我想创建一个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;
}
}
}
}
}
您的程序可能无法正常运行,因为这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());
演示。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句