2015-03-02 58 views
0

我正在处理的任务的一部分是让我通过一个方法来传递数组,这个方法一次计算最后一个数组中的元素的平均值。创建一个平均数组

例如,假设Array1包含{1,2,3,4,5,6} 该方法将计算{1,2,3,4,5}的平均值,然后计算{2,3,4,5} 4,5,6}

然后,该方法将取这些平均值并将它们放入一个新的数组中,并将该数组传回主。

我只是不知道从哪里开始。我能想到的最多的是我需要使用嵌套循环。

是的,这是我编程的第一年。

回答

0

欢迎来到Stack Overflow,Tony!在Stack Overflow中,我们真的鼓励用户提供一些努力或研究的证据,在将来的文章中记住这一点:)

让我们从逻辑上思考这个问题。

我们想要从array[0]array[n-2](您使用n-2,因为索引n-1实际上保持值'6')的数组平均值开始。

第二部分。从array[1]开始,然后转到array[n-1]
一旦我们知道了这一点,就可以取平均值并将其返回。

没有必要对嵌套循环在这里,记住这个概念而设计,很多的眼泪将被保存:保持简单

这里是被张贴了类似的问题:How to minpulate arrays and find the average


这里我想出了一个解决方案。当您处于程序的设计阶段时,您想考虑如何让代码可重用。可能有一段时间你会有一个复杂的程序,许多部件需要用不同的数据执行相同的操作。这被称为代码重用性并掌握它会让你的生活更轻松。

public static void main(String[] args) { 
    int [] arr = new int [] {1, 2, 3, 4, 5, 6}; //Stores the numbers we need to average 

    //We get the Lower-Average by starting at index 0, going to index n-2 
    System.out.println ("Lower-Average: " + average(0, arr.length - 2, arr)); 

    //We get the Upper-Average by starting at index 1, going to index n-1 
    System.out.println ("Upper-Average: " + average(1, arr.length - 1, arr)); 
} 

/* 
* This method accepts a start index, end index, and an array to operate on 
* The average is calculated iteratively and returned based on number of elements provided 
*/ 
public static double average (int startIndex, int endIndex, int [] array) { 
    double avg = 0; //Stores the average 
    int counter; //Used to hold number of elements iterated through 

    for (counter = startIndex; counter <= endIndex; counter++) { 
     avg += array[counter]; //Summation for the average 
    } 
    return avg = avg/counter; //Calculate the average and return it to caller 
} 

输出:

Lower-Average: 3.0 
Upper-Average: 3.3333333333333335