用java求fibonacci数组,用数组计算斐波那契数

// I am learning about recursion in Java.

/** I am trying to calculate the 45th Fibonacci number by using an array to shorten the time used, which does not work out well...

error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 45

at Auf1.fib2(Auf1.java:25)

at Auf1.main(Auf1.java:49)

**/

public class Auf1 {

public static long[] feld;

public static long fib2(long n) {

if ((n == 1) || (n == 2)) {

return 1;

} else {

if (feld[(int) n] != -1) {

return feld[(int) n];

} else {

long result = fibo(n - 1) + fibo(n - 2);

feld[(int) n] = result;

return result;

}

}

}

public static void main(String[] args) {

long n = 45;

feld = new long[(int) n];

for (int i = 0; i < n; i++) {

feld[i] = -1;

}

long result = fib2(n);

System.out.println("Result: " + result);

}

}

解决方案

The Array indices starts with 0.

You create a array of size 45. Valid array indices are 0,1...44. In your first call of fib2 your check if array[45] equals -1. array[45] is not a valid index and will result in an IndexOutOfBoundException.

change the following lines:

(feld[(int) n] != -1)

to

(feld[(int) n - 1] != -1)

and the line

feld[(int) n] = result

to

feld[(int) n - 1] = result;

BTW There is a syntax error. The recursive call should be fib2(n-1) + fib2(n-2) and not fibo(n-1) + fibo(n-2)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值