gpt4 book ai didi

java - 斐波那契作业 - java

转载 作者:行者123 更新时间:2023-11-28 21:00:52 24 4
gpt4 key购买 nike

我们必须创建一个斐波那契系统。你能告诉我我做错了什么吗?它在 while 循环下给我一个错误,但我确信这是我构造变量的方式。

public class Chapter3 {
public static void main (String args[]){
int numFn;//CREATE NUMBER OF FN, SUM OF FN, AND AVERAGE
int average[]=new int [0];
int sumFn []=new int [0];//ARRAY OF SUMFN
numFn = 1;//ASSIGN FN AS 1
int x = 0;//NUMBERIN SIDE FN ARRAY
int Fn []=new int[16];//CREATE FN ARRAY
Fn [0]=0;

while (numFn <15){
Fn[x]= Fn[x]-Fn[x-1];//SET THE CURRENT FN NUMBER
sumFn [x]=sumFn[x]+(sumFn[x-1]+Fn[x]);//SET CURRENT SUMFN NUMBER
average [x]= sumFn[x]/numFn;

System.out.println(numFn +"/t" +Fn+"/t" +sumFn+"/t" +average);
x++;
numFn++;
}
}
}

好吧,我根据你们的建议对其进行了更改,但第一个输出是 1 然后是 0,使用以下代码:

           public class Chapter3 {
public static void main (String args[]){
int numFn;//CREATE NUMBER OF FN, SUM OF FN, AND AVERAGE
int average[]=new int [16];
int sumFn []=new int [16];//ARRAY OF SUMFN
numFn = 1;//ASSIGN FN AS 1
int x = 1;//NUMBERIN SIDE FN ARRAY
int Fn []=new int[16];//CREATE FN ARRAY
Fn [0]=0;



while (numFn <15){
Fn[x]= Fn[x]-Fn[x-1];//SET THE CURRENT FN NUMBER
sumFn [x]=sumFn[x]+(sumFn[x-1]+Fn[x]);//SET CURRENT SUMFN NUMBER
average [x]= sumFn[x]/numFn;

System.out.println(numFn +"\t" +Fn[x]+"\t" +sumFn[x]+"\t" +average[x]);
x++;
numFn++;
}


}

最佳答案

几个问题:

  1. new int[0] 表示一个空数组,这不是你想要的 想要。
  2. 第一次循环执行时X值为0,所以Fn[X-1]为Fn[-1],即 会导致 ArrayOutOfBoundException。

您能否更明确地说明您遇到的错误?

关于java - 斐波那契作业 - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7860054/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com