这是它应该模拟2次骰子的代码5次。
import java.util.*;
public class RollDice {
static double die1;
static double die2;
static double sum;
public static void main (String[] args) {
String output = "";
for (int i =0; i<5; i= i+1) {
die1 = (Math.random()*6)+1;
die1 = (int) die1;
die2 = (Math.random()*6)+1;
die2 = (int)die2;
System.out.println("die 1 "+ die1+" die 2 "+ die2);
sum = die1+die2;
System.out.println("The sum is "+ sum);
if(i>5) break;
}
}
}
我需要计算所有卷的平均值而不是每个卷的平均值,因此输出显示卷的总和和所有卷的平均值。
答案 0 :(得分:1)
您可以简化
die1 = (Math.random()*6)+1;
die1 = (int) die1;
要
die1 = (int) ((Math.random() * 6) + 1);
但如果你想要精确的值,你就不需要将它强制转换为整数,那就是截断(除去)你的小数位。
总结所有卷,
int total = 0;
int maxRolls = Integer.MAX_VALUE; //lol
for (int roll = 1; roll <= maxRolls; roll++) {
// roll your dice
total += (die1 + die2);
}
平均
double average = (total / maxRolls);
输出
System.out.println("Total: " + total + " Average: " + average + " Rolls: " + maxRolls);
欢迎你,现在做自己的功课
答案 1 :(得分:0)
如果平均而言你的意思是所有骰子卷的平均值,你可以将它总结为所有卷并除以10。
static double total = 0;
// in your for loop
total += sum;
// after the loop
System.out.println("Average: "+(total/10));
答案 2 :(得分:-1)
可能是这样的:
public class RollDice {
public void main(String[] args) {
int total;
for(int i = 1; i < 6; i++) {
int die1 = roll ();
int die2 = roll();
System.out.println("die 1 = " + die1 + " and die2 = " + die2);
int sum = die1 + die2;
System.out.println("the sum is " + sum);
total += sum;
}
double avg = total / 5.0d;
System.out.println("the avg is " + avg);
}
public int roll() {
return Math.floor(Math.random()*6 + 1.0d);
}
}