2011-12-07 33 views
-2
System.out.println(type integer); 
int 1 = kb.nextInt(); 
System.out.println(type integer); 
int 2 = kb.nextInt(); 
System.out.println(type integer); 
int 3 = kb.nextInt(); 
System.out.println(type integer); 
int 4 = kb.nextInt(); 
int [] integers = new int {1 + 2 + 3 + 4} 
System.out.println(integers/numberofinputs?); 

是的我不知道如何劃分總數的數量在數組內。如何製作一個採用整數數組並返回平均數的方法?

+3

甚至沒有一條線沒有錯誤。你甚至不試圖編譯任何東西嗎? – Kapep

回答

3

問:

如何使以整數數組,並返回 平均數量的方法?

答:

public static double getAverage(int[] array) 
{ 
    int sum = 0; 
    for(int i : array) sum += i; 
    return ((double) sum)/array.length; 
} 
+2

請注意,這將截斷平均數的小數點。例如,2,3和5的「平均值」將是「3」而不是「3.3333 ....」。在分割之前將其轉換爲雙精度以避免截斷。 –

+0

@Jonathan不能_just_強制轉換爲'double',因爲函數被聲明爲返回int。 –

+0

@JonathanNewmuis你是對的! –

0

遞歸

double getAverage (int [ ] array) 
{ 
    return (double) (getSum (array , 0 , array . length))/array . length ; 
} 

int getSum (int [ ] array , int floor , int ceil) 
{ 
    if (ceil - floor < 1) { throw new RuntimeException () ; } 
    else if (ceil - floor == 1) 
    { 
     return array [ floor ] ; 
    } 
    else 
    { 
     return getSum (floor , (floor + ceil)/2) + getSum ((floor + ceil)/2 , ceil) ; 
    } 
} 
+0

...神聖的廢話。沒有看到這個答案。 –

0

要嘗試並引導你在正確的方向,你會想嘗試打破這一成幾部分。我建議列出所有你需要做的事情來完成這項任務。

  • 獲取計算平均值的值,將它們保存到數組中。
    • 這將需要知道數據來自哪裏(文件,輸入等)。
    • 它可能還需要知道程序運行時會給出多少個值。
  • 通過數組的一個元素,計算所有值的總和。
    • 你可以按照Eng.Fouad的例子來做到這一點。
  • 一旦你得到了總和,只需除以輸入到程序中的值的數量。這是你的最終平均值。

它看起來像你最大的問題是試圖從用戶獲取值。你正在使用掃描儀(我從標準輸入或命令行假設)正確的軌道,但現在你需要將多個值保存到一個數組(或一個列表或其他)。

我給你一個使用數組的示例(這將需要知道將會提供多少個值)。注 - 這不會編譯。在嘗試使其正常工作之前,您必須填寫詳細信息。

Scanner scanner = ... ; # Fill in the '...' 
int totalElements = 10; # TODO - Determine what this value should be, or get it from the user 
double[] values = new double[totalElements]; # Make an array with totalElements amount of slots 
int counter = 0; 

while (/* fill this in with scanner method to check for another double*/) { 
    values[counter] = /* fill in with scanner method to read a double*/; 
    /* fill in with a way to increase the counter by 1 */ 
} 

從這裏開始,您可以開始計算平均值的函數。

相關問題