# homework 1 coded by kazma

unknown
java
2 years ago
3.2 kB
1
Indexable
Never
```import java.util.*;

public class App {

static int num = 10; // 數組個數

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
// int[] arr = new int[] { 45, 46, 74, 12, 32, 74, 50, 3, 87, 24 };
int[] arr = new int[num];
int tot=0, rnd = 100; //總和 亂數最大值 紀錄people目前長度

Random randomObject = new Random(); // create random object
for (int n=0; n < num; n++) //產生亂數測資
arr[n] = randomObject.nextInt(rnd);

for(int n=0; n<num; n++){ //數組加總
// arr[n] = sc.nextInt();
tot += arr[n];

}System.out.println();

Arrays.sort(arr); //數組排序
System.out.println(Arrays.toString(arr)); //Debug印出數組

double arg = (double)(tot)/(double)(num);// 平均數

//眾數
//  暫存相同數長度  目前最大相同數長度  最大數長度代表的數字
int peopleLen = 0, peopleLenMax = 0, peopleMax = 0;
for(int i = 0; i<arr.length-1; i++){
//若目前數字=下一個數字
if(arr[i] == arr[i+1]){
peopleLen += 1; //暫存相同數+1
}
// 當暫存相同數長度 > 目前最大相同數長度
else if(peopleLen > peopleLenMax){
peopleLenMax = peopleLen; // 目前最大相同數長度=暫存相同數長度
peopleMax = arr[i]; //紀錄最大數長度代表的數字
peopleLen = 0; // 暫存相同數歸零
}
else //目前數字!=下一數字 而且 暫存相同數長度 < 目前最大相同數長度
peopleLen = 0;
}

double[] quar = new double[3]; //四分位數
quar[1] = midNum(arr); // 中位數
quar[0] = midNum(Arrays.copyOfRange(arr, 0, arr.length/2));
quar[2] = midNum(Arrays.copyOfRange(arr, arr.length%2==0 ? arr.length/2 : arr.length/2+1, arr.length));

double diff = 0; // 差平方和
//標準差
for(int i=0; i<num; i++){
diff += Math.pow((arr[i] - arg), 2);
}

System.out.println(String.format("最大值: %d\t最小值: %d\t中位數: %.1f", arr[num-1], arr[0], quar[1]));
if (peopleLen != peopleLenMax)
System.out.println(String.format("眾數為: %d", peopleMax));
else
System.out.println("此數組不存在眾數!!");
System.out.println(String.format("樣本標準差為 %.3f\t算術平均數為 %.3f\t", Math.pow(diff/num, 0.5), arg));
System.out.println(String.format("四分位數: %.1f %.1f %.1f", quar[0], quar[1], quar[2]));
System.out.println(String.format("四分位距: %d\t", (int)(quar[2] - quar[0])));

sc.close();
}

public static double midNum(int[] arr){ //取中位數
int num = arr.length;
double mid, temp = (arr[num / 2] + arr[(num / 2) - 1]);
if (num % 2 == 0)
mid = (temp / 2);
else
mid = arr[(num / 2)];
return mid;
}
}
```