[英]Finding the mode of a randomly generated array of 10 numbers
我正在嘗試制作這個程序
public class Statistics {
public static void main(String[] args) {
final int SIZE = 10;
int sum =0;
int[] numArray= new int [SIZE];
for (int c=0; c < SIZE; c++)
{
numArray[c]=(int)(Math.random()*6+1);
System.out.print( numArray[c]+ " ");
sum+=numArray[c];
}
System.out.println("\nSum of all numbers is " + sum);
System.out.println("\n Mean of numbers is " + (sum) / 5);
}
}
計算隨機生成的數組的模式。
我已經看到源代碼發布在它們使用稱為compactmode的單獨方法的地方,但是我不知道將第二個方法放置在代碼中的何處。 抱歉,編程時我非常環保。 我被教為Java的第一門語言,到目前為止,它是壓倒性的。
如果有人可以發布帶有詳細說明/解釋的語法,我將非常感激。
該模式很容易計算。 假設您的輸入是有界的,一種方法是簡單地使用一個數組來跟蹤每個數字的出現次數:
int[] data; //your data bounded by 0 and MAX_VALUE
int[] occurrences = new int[MAX_VALUE+1];
for ( int datum : data ) {
occurrences[newNumber]++;
}
然后找出出現次數最高的索引。
int maxOccurrences = Integer.MIN_VALUE;
int mode = -1;
for ( int i = 0; i < occurrences.length; i++ ) {
if ( occurrences[i] > maxOccurrences ) {
maxOccurrences = occurrences[i];
mode = i;
}
}
您將不得不對此進行調整以處理多種模式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.