我正在尝试创建一个程序,该程序可以找到斐波那契数列低于400万的偶数之和。我知道有一种更简单的方法可以做到这一点,但我想看看它是否适用于数组。我之前从未真正使用过数组,因为我对Java很新,这就是为什么我想看看这是否适用于数组。我遇到的主要问题是for语句。我怎样才能看出fibarray [i]的含量是否小于4000000?
另外,如果我使用fibarray = new int[i]
public static void main(String[] args) {
int[] fibarray;
int numcount = 0;
int i = 0;
long sum = 0;
fibarray = new int[i];
fibarray[0] = 0;
fibarray[1] = 1;
for(i = 0 , fibarray[i] < 4000000, i++;;){
fibarray[i] = fibarray[i - 1] + fibarray[i - 2];
}
}
如果这听起来真的很愚蠢,我道歉。 任何帮助将非常感激。 感谢。
答案 0 :(得分:0)
好吧,你需要用i = 2开始你的for循环。而for循环应该是这个语法
for(i = 2; fibarray[i] < 4000000; i++) {
fibarray[i] = fibarray[i - 1] + fibarray[i - 2];
}
答案 1 :(得分:-1)
查看代码中的评论:
public static void main(String[] args){
/*************************
* comments on your code
int[] fibarray; //use right java naming convention
int numCount = 0; //this variable is never used
int i = 0;
long sum = 0;
fibarray = new int[i];//you initialize an array of size 0.
fibarray[0] = 0; //you can't set value to array of size 0
fibarray[1] = 1; //you can't set value to array of size 0
//wrong syntax
for(i = 0 , fibarray[i] < 4000000, i++;;){
//use for(i = 0 ; fibarray[i] < 4000000; i++){
fibarray[i] = fibarray[i - 1] + fibarray[i - 2];
}
*******************************/
//Alternative code
//you don't need to keep all Fibonachi numbers found.
//you only use 3 numbers for every calculation
int size = 3;
int totalLimit = 4000000;
int[] fibArray = new int[size];
fibArray[0] = 0; fibArray[1] = 1;
int total = 0;
while( true ) {
fibArray[2] = fibArray[0] + fibArray[1] ;
if((fibArray[2]%2) ==0) { //even number
if((total + fibArray[2]) >= totalLimit) {
break;
}
total += fibArray[2];
}
fibArray[0] = fibArray[1] ;
fibArray[1] = fibArray[2] ;
}
System.out.println("Total "+ total );
}
根据需要,请不要犹豫要求澄清。