我该怎么做?我需要使用一个next()方法创建一个Fibonacci类,该类返回下一个Fibonacci字符串值。后续呼叫应返回:0、1、1、2、3、5、8等。
该程序从用户那里获取一个整数,并返回指定数量的字符串值。应使用数组进行计算。
public class Fibonacci {
final long[][] A = {{1, 1}, {1, 0}};
public static void main(String[] args) {
System.out.print("Enter the n th word of the sequence: ");
long n = initialStatement(readValue());
Fibonacci f = new Fibonacci();
for (int i = 0; i < n; i++) {
long[][] b = f.next();
System.out.print(b[0][1]);
}
}
public static long readValue() {
Scanner scanner = new Scanner(System.in);
return scanner.nextLong();
}
public static long initialStatement(long n) {
do {
if (n == 0 || n == 1) {
return n;
} else if (n < 0) {
System.out.print("Wrong value, please enter correct value: ");
n = Fibonacci.readValue();
}
} while (n < 0);
return n;
}
public long[][] next() {
long[][] a =new long[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
a[i][j] += a[i][j] * A[j][i];
}
}
return a ;
}
}
您的矩阵令人困惑。
这是使用两个int而不是matrix的代码的简单更改。
测试一下,让我知道。
public class Fibonacci {
long i = -1; // clone of the loop counter i
long fibo1 = 1;
long fibo2 = 1;
public void main(String[] args) {
System.out.print("Enter the n th word of the sequence: ");
long n = initialStatement(readValue());
Fibonacci f = new Fibonacci();
for (int i = 0; i < n; i++) {
System.out.print(f.next());
}
}
public static long readValue() {
Scanner scanner = new Scanner(System.in);
return scanner.nextLong();
}
public static long initialStatement(long n) {
do {
if (n == 0 || n == 1) {
return 1; // fibo(0) == fibo(1) == 1
} else if (n < 0) {
System.out.print("Wrong value, please enter correct value: ");
n = Fibonacci.readValue();
}
} while (n < 0);
return n;
}
public String next() {
i++; // simulation of loop i because it is not a param of next()
if(i >= 2) {
long aux = fibo1 + fibo2;
fibo1 = fibo2;
fibo2 = aux;
}
return ""+ fibo2;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句