我对 Java 编程非常陌生,我需要帮助将 double[] arrayP 或问题的百分比四舍五入到小数点后两位。对程序本身的任何反馈也非常感谢。
谢谢!
It looks like this:
Sum Frequency Percentage
2 1042 2.8944444444444444
3 2003 5.563888888888889
4 3032 8.422222222222222
5 3953 10.980555555555556
6 4971 13.808333333333334
7 6020 16.72222222222222
8 4986 13.850000000000001
9 4022 11.172222222222222
10 2979 8.275
11 1988 5.522222222222222
12 1003 2.786111111111111
Should look like this:
Sum Frequency Percentage
2 1034 2.87
3 1987 5.52
4 3028 8.41
5 3881 10.78
6 4912 13.64
7 6135 17.04
8 5060 14.06
9 4032 11.20
10 2965 8.24
11 2003 5.56
12 963 2.68
这是我的代码:
public class Assignment_Roll36 {
public static void main(String[] args) {
//create table
System.out.println("Sum\t" + "Frequency" + "\tPercentage");
//create an array to store sum
int[] arraySum = new int[35999];
//counters
int[] sumFreq = {0,0,0,0,0,0,0,0,0,0,0};
//loop for dice & sum & storage in array
for(int i = 0; i < 35999; i++){
//create random roll dice1 & dice2
int dice1 = (int)(Math.random() * 6 + 1);
int dice2 = (int)(Math.random() * 6 + 1);
//sum for dice 1 & dice2
int sum = dice1 + dice2;
//store sum into array
arraySum[i] = sum;
//if to send to counter
if (arraySum[i] == 2) {
sumFreq[0]++;
} else if (arraySum[i] == 3) {
sumFreq[1]++;
} else if (arraySum[i] == 4) {
sumFreq[2]++;
} else if (arraySum[i] == 5) {
sumFreq[3]++;
} else if (arraySum[i] == 6) {
sumFreq[4]++;
} else if (arraySum[i] == 7) {
sumFreq[5]++;
} else if (arraySum[i] == 8) {
sumFreq[6]++;
} else if (arraySum[i] == 9) {
sumFreq[7]++;
} else if (arraySum[i] == 10) {
sumFreq[8]++;
} else if (arraySum[i] == 11) {
sumFreq[9]++;
} else if (arraySum[i] == 12) {
sumFreq[10]++;
}
}
**double[] arrayP = new double[11];
for (int a=0;a<11; a++){
double total = 36000;
double value = (sumFreq[a] / total);
double percent = value * 100;
arrayP[a] = percent;**
}
//for loop ends
int[] array1 = {2,3,4,5,6,7,8,9,10,11,12};
for(int y = 0; y < 11; y++){
System.out.println(array1[y] + "\t" + sumFreq[y] + "\t\t" + arrayP[y]);
}
}
}