斐波纳契家庭作业 - java
问题描述:
我们必须创建一个斐波那契系统。你能告诉我我做错了什么吗?它在while循环下给了我一个错误,但我确定这是我构造变量的方式。斐波纳契家庭作业 - java
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++;
}
}
}
答
几个问题:
- new int [0]意味着一个空数组,它不是你想要的 。
- 在第一次循环执行时X值为0,所以Fn [X-1]为Fn [-1],其中 将导致ArrayOutOfBoundException。
您能否更清楚地了解您遇到的错误?
答
您的sumFn数组声明的长度为0.因此,无论何时尝试向其中添加任何元素,您都将获得ArrayOutOfBoundException
。
答
还有几个代码的问题,即使修复导致ArrayIndexOutOfBoundsException的问题,我怀疑它会工作。首先,你必须初始化你使用正确的大小的数组:
int average[]=new int [16];
int sumFn []=new int [16];
的“X”变量应在1开始:
int x = 1;
而且,目前还不清楚你想要什么打印,反正println()
说法应该是固定的
System.out.println(numFn +"\t" +Fn[x]+"\t" +sumFn[x] + "\t" +average[x]);
答
我觉得这是你在做什么(此代码1和1开始打印前20项)后...
public class Fibonacci {
public static void main(String[] args) {
int n0 = 1, n1 = 1, n2;
System.out.print(n0 + " " + n1 + " ");
for (int i = 0; i < 18; i++) { // Loop for the next 18 terms
n2 = n1 + n0; //The next term is the sum of the previous two terms
System.out.print(n2 + " ");
n0 = n1; // The first previous number becomes the second previous number...
n1 = n2; // ...and the current number becomes the previous number
}
System.out.println();
}
}
至于你的错误,请阅读其他答案。他们的建议很好。 :)
答
这对解决Fibonacci序列练习很有帮助。但是不打印零点,所以我在这里添加...
/*
* FibonacciSequence.java
* ----------------------
* This program displays the values in the Fibonacci sequnece from F0 to F15.
*/
import acm.program.*;
public class FibonacciSequence extends ConsoleProgram{
public void run() {
int n0 = 1;
int n1 = 1;
int n2;
println("0" + "\n" + n0 + "\n" + n1);
for (int i = 0; i < 13; i++) { // Loop for the next 18 terms
n2 = n1 + n0; //The next term is the sum of the previous two terms
println(n2 + " ");
n0 = n1; // The first previous number becomes the second previous number...
n1 = n2; // ...and the current number becomes the previous number
}
println();
}
}
为什么你不告诉_us_你有什么错误? –
拼写斐波那契。 – akappa
'new int [0]'是一个只有0项的数组,这肯定是错误的。 – Vlad