![](/img/trans.png)
[英]Find the average of numbers in an array and find the numbers greater than the average
[英]I am trying to use a method in order to find which numbers in the array are greater than 20 and return a percentage
到目前為止,這是我寫的內容,但我不確定從這里去哪里:
public double findPercentageGreaterThanTwenty(int[] intArray) {
double average = 0;
for (int i = 0; i < intArray.length; i++) {
sum = i;
if (intArray[i] > 20) {
average = (average + intArray[i]) / sum;
}
}
return average;
}
平均值與無關。 當數字大於20時,只需增加計數即可。
public double findPercentageGreaterThanTwenty(int[] intArray) {
double count=0;
for (int i=0; i < intArray.length; i++) {
if (intArray[i] > 20) {
count++;
}
}
return count / intArray.length * 100; // returns the result in %
}
表達式count / intArray.length
返回介於0
(即0%)和1
(即100%)之間的值。 將其乘以100可得出百分比結果。
對於其他人,還有使用Stream-API的Java 8解決方案。 但是,我建議您首先學習所有基礎知識的解決方案:)
int[] array = {1, 2, 5, 9, 12, 23, 25, 31, 33, 48};
long count = Arrays.stream(array).filter(n -> n > 20).count();
System.out.println(count / array.length * 100);
平均值與20以上的數字的百分比無關。 您需要做的就是對它們進行計數,然后將其除以數組中元素的總數:
public double findPercentageGreaterThanTwenty(int[] intArray) {
int above20 = 0;
for (int i = 0; i < intArray.length; i++) {
++above20;
}
return ((double) above20) / intArrary.length;
}
請注意,這將返回一個介於0和1之間的雙精度數。如果您想要一個介於0和100之間的百分比,只需乘以100。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.