gpt4 book ai didi

java - 返回数据不带两位小数 :Rounding Doubles

转载 作者:行者123 更新时间:2023-11-29 05:38:43 25 4
gpt4 key购买 nike

我是 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]);

}

}
}

最佳答案

存储 的值与打印 的视觉表示之间存在差异(在这种情况下,您的System.out.println调用)。

一般来说,您希望在代码中保持数据的精确性,然后根据需要对其进行格式化以便打印。对于 double ,您可以使用类似的东西:

DecimalFormat df = new DecimalFormat("#.##");
System.out.println("Value is " + df.format(value));

关于java - 返回数据不带两位小数 :Rounding Doubles,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18517674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com