【问题标题】:How can I perform this type of thing? (java)我怎样才能执行这种类型的事情? (爪哇)
【发布时间】:2014-08-18 13:47:35
【问题描述】:

我现在正在学习java,在这一章的一维数组中我遇到了很多问题。 在这个问题中我需要做的是检测数组中是否有相同数量的数字高于平均值而不是低于平均值。现在,我不知道的是,在我检测到数组的中间之后,我如何计算平均值,因为我不知道如何将所有数字相加,记住我不能只说array[1]+array[2]+array[3],因为我根本不知道有多少数组元素有...

【问题讨论】:

  • 你了解循环吗?
  • 您的问题标题无法告诉我们您的问题是什么。一些语法也会有所帮助。
  • 所以,您的问题似乎是“我如何平均一个整数数组”?
  • 你能不能试着改写你的问题,理解你想要什么有点混乱。

标签: java arrays


【解决方案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;
}

【讨论】:

  • 我认为 OP 想要计算高于和低于平均值的数字,而不是仅仅获取数组中数字的总数或平均值,所以我在回答中反映了这一点。
  • @OP 这能回答你的问题吗?这几天没有你的回复。
猜你喜欢
  • 2012-10-11
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-17
相关资源
最近更新 更多