用数组计算斐波那契数

编程入门 行业动态 更新时间:2024-10-26 00:30:58
本文介绍了用数组计算斐波那契数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

///我正在学习Java中的递归。 / **我正在尝试通过使用数组来缩短使用的时间来计算第45个斐波那契数,这不能很好地解决... 错误消息:线程 main java.lang.ArrayIndexOutOfBoundsException:45 at Auf1.fib2(Auf1.java:25) at Auf1.main(Auf1.java:49) ** /

// 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); } }

推荐答案

数组索引以0开头。您将创建一个大小为45的数组。有效的数组索引为0,1 ... 44。在第一次调用fib2时,检查array [45]是否等于-1。数组[45]无效,将导致IndexOutOfBoundException。

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.

更改以下行:

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

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

和行

feld[(int) n] = result

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

BTW存在语法错误。递归调用应为 fib2(n-1)+ fib2(n-2)而不是 fibo(n-1)+ fibo(n- 2)

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)

更多推荐

用数组计算斐波那契数

本文发布于:2023-11-29 01:02:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644662.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!