2015-03-02 83 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