我怎么能做这种事情? (Java)的

时间:2014-08-18 13:47:35

标签: java arrays

我正在研究java,我在1维数组的这一章中遇到了很多问题。 我在这个问题中需要做的是检测数组中的数字是否高于平均值以上的数字。现在,我不知道,在我检测到阵列的中间部分之后,我怎么能计算平均值,因为我不知道如何将所有数字加在一起,记住我只能说array[1]+array[2]+array[3]因为我根本就不知道有多少数组元素...

1 个答案:

答案 0 :(得分:1)

使用for循环:

double total = 0; //Total of all the numbers in the array
double average; //Average of all the numbers in the array
int belowCount = 0; //Number of numbers below the average
int aboveCount = 0; //Number of numbers above the average
int sameCount = 0; //Number of numbers at the average
for(int i = 0; i < array.length; i++){
    total += array[i];
}
average = total/array.length;
for(int i = 0; i < array.length; i++){
    if(array[i] < average){
        belowCount++;
    }
    else if (array[i] > average){
        aboveCount++;
    }
    else{
        sameCount++;
    }
}

if(belowCount==aboveCount)
{
    return true;
}
else 
{
    return false;
}