2017-02-15 43 views
1
public static void main(String[] args) { 
    Scanner ulaz=new Scanner(System.in); 
    System.out.println("Enter number of array elements: "); 
    int n=ulaz.nextInt(); 
    int[]array=new int[n]; 
    System.out.println("Insert array elements: "); 
    int sum=0; 
    for (int i=0;i<n;i++){ 
     array[i]=ulaz.nextInt(); 
     sum+=array[i]; 
    } 
    int arithmeticmean=sum/n; 
    for(int i=0;i>arithmeticmean;i++){ 
    System.out.print(i); 
    } 
} 

我的問題是:爲什麼我看不到有多少元素比這個數組的算術平均值大?我做錯了什麼? 在此先感謝您的幫助java中的單維數組,並試圖獲得數組中的多少數大於算術平均數

+0

代替'arithmeticmean'的第二個循環使用'array.size'。 – orvi

回答

2

你比較

for(int i=0;i>arithmeticmean;i++) 

,而不是比較iarithmeticmean的,比較array[i]

for(int i=0;i< array.length; i++) { 
    if (array[i] > arithmeticmean) { 
     System.out.println(array[i]); 
    } 
} 

如果你想知道有多少數量滿足這一要求,那麼你需要使用一個計數器:

int counter = 0; 
for(int i=0;i< array.length; i++) { 
    if (array[i] > arithmeticmean) { 
     counter++; 
     System.out.println(array[i]); 
    } 
} 
System.out.println("Amount of items that are greater than arithmetic mean: " + counter); 
+0

謝謝,現在我意識到我錯了。這是完全錯誤的想法如何得到想要的結果。 – Mapet

1

要打印大於算術平均值的值,需要遍歷所有值並僅打印大於算術平均值的值。

// Loop through all values 
for (int i = 0;i < array.length; i++) { 

    // Check if the value is bigger than the arithmetic mean 
    if (array[i] > arithmeticmean) { 
     System.out.print(i); 
    } 
} 
+0

Thansk讓你到Davide,你們兩個都很有幫助。儘快這樣做,我會像Java一樣有幫助。 – Mapet