编写一个程序来计算前10个Fibonacci数,并将结果存储在一维数组中。在第二个数组中计算并存储系列中相邻数字的平均值。第一个数组应包含整数值和第二个浮点值。以整齐的格式输出两个数组的内容
public static void main(String[] args) {
//number of elements to generate in a series
int limit = 10;
long[] series = new long[limit];
//create first 2 series elements
series[0] = 1;
series[1] = 1;
//create the Fibonacci series and store it in an array
for(int i=2; i < limit; i++){
series[i] = series[i-1] + series[i-2];
}
//print the Fibonacci series numbers
System.out.println("Fibonacci Series upto " + limit);
for (int i = 0; i < limit; i++) {
System.out.print(series[i] + " ");
}
}
好的,所以第一部分工作正常,但现在创建一个数组来计算平均值对我来说有点棘手。到目前为止我试过了。
int[] numbers = new int[]{1,1,2,3,5,8,13,21,34,55};
int sum=0;
for (int i = 0; i < numbers.length ; i++) {
sum = (int) (sum + numbers[i]);
double average = (double)sum/numbers.length;
System.out.println("Average value of array elements is : " + average);
}
但它不能很好地工作。有人能给我一些启示吗?
答案 0 :(得分:2)
您不应计算for loop
内的平均值。将average
移到循环外部,以便在sum
准确时计算。
int[] numbers = new int[]{1,1,2,3,5,8,13,21,34,55};
int sum=0;
for(int i=0; i < numbers.length ; i++){
sum = (int) (sum + numbers[i]);
}
double average = (double)sum/numbers.length;
System.out.println("Average value of array elements is : " + average);
答案 1 :(得分:1)
试试这个:
int[] numbers = new int[]{1,1,2,3,5,8,13,21,34,55};
int sum=0;
for (int i = 0; i < numbers.length - 1; i++) {
sum = (int) (sum + numbers[i]);
double average = sum/2.0;
System.out.println("Average value of array elements is : " + average);
}