我必须为我的java类制作一个程序,掷出2个骰子,然后将其观察到的出现百分比与预期出现百分比进行比较。预期观察到的百分比将四舍五入到小数位。但是,每当我运行该程序时,观察到的百分比总是显示为“%.2fn,[percentage]”。这是我的(虽然有些混乱)代码:
import java.util.*;
public class Problem1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random roll1 = new Random();
Random roll2 = new Random();
int die1;
int die2;
int sum;
double zero = 0;
double one = 0;
double two = 0;
double three = 0;
double four = 0;
double five = 0;
double six = 0;
double seven = 0;
double eight = 0;
double nine = 0;
double ten = 0;
double[] occurances = new double [11];
double[] percentages = new double [11];
percentages[0] = 2.78;
percentages[1] = 5.56;
percentages[2] = 8.33;
percentages[3] = 11.11;
percentages[4] = 13.89;
percentages[5] = 16.67;
percentages[6] = 13.89;
percentages[7] = 11.11;
percentages[8] = 8.33;
percentages[9] = 5.56;
percentages[10] = 2.78;
System.out.print("How many times would you like to roll the dice? ");
int repeat = keyboard.nextInt();
for (int i = 0; i < repeat; i++) {
die1 = roll1.nextInt(6);
die2 = roll2.nextInt(6);
sum = die1 + die2;
if (sum == 0) {
zero++;
occurances[0] = zero;
} else if (sum == 1) {
one++;
occurances[1] = one;
} else if (sum == 2) {
two++;
occurances[2] = two;
} else if (sum == 3) {
three++;
occurances[3] = three;
} else if (sum == 4) {
four++;
occurances[4] = four;
} else if (sum == 5) {
five++;
occurances[5] = five;
} else if (sum == 6) {
six++;
occurances[6] = six;
} else if (sum == 7) {
seven++;
occurances[7] = seven;
} else if (sum == 8) {
eight++;
occurances[8] = eight;
} else if (sum == 9) {
nine++;
occurances[9] = nine;
} else if (sum == 10) {
ten++;
occurances[10] = ten;
}//if
}//for
System.out.println("roll observed expected");
for (int i = 0; i < occurances.length; i++) {
float observed = (float)(occurances[i]/repeat) * 100;
System.out.println((i+2)+" %.2fn"+observed+"% "+percentages[i]+"%");
}
}
}
我如何在每个预期百分比前都删除“%.2fn”,使其仅保留小数点后两位?我以为
%.2fn
是这类事情的正确表示法,但不适用于此事情。 最佳答案
println
方法对诸如%.2f
这样的格式化模式一无所知。它认为这是您要打印的文字字符串。
改为查看the printf
method,它了解格式模式。