这些数据的输出是随机的,我为此创建了一个函数。我想要记录多少次的“尝试”它得到骰子一个比骰子连续两次两次。因此,当它连续两次变大时,我希望它打印出来(“d1比d2连续两次大”,“需要”+试用+“)。到目前为止,我有这个,但被卡住了:
public static int Dice() {
return (int)(Math.random() * 6.0) + 1;
}
public static void main(String[] args) {
int d1 = Dice();
int d2 = Dice();
int trials = 0;
for (int i = 0; i < 100000; i++) {
if (t1 > t2) {
trials++;
if (t1 > t2) {
trials++
}
}
}
System.out.println(trials);
}
} 发布于 2018-10-17 19:26:24
欢迎来到这里!这应该能行。看看你做错了几件事的评论和一些解释。
public static int Dice() {
return (int)(Math.random() * 6.0) + 1;
}
public static void main(String[] args) {
// initialize variables to be updated in the loop
int trials = 0;
Boolean lastTimeD1WasGreater = false;
for (int i = 0; i < 100000; i++) {
// always increment the counter!
trials++;
// you had the wrong variable names here.
// also they must be INSIDE the loop or else they would always come out the same
int d1 = Dice();
int d2 = Dice();
if (d1 > d2) {
if (lastTimeD1WasGreater) {
// if it was greater both last time and this time then we're done!
System.out.println("it took " + trials + " trials.");
break;
} else {
// otherwise set this variable so we can be on the lookout next time.
lastTimeD1WasGreater = true;
}
} else {
// d1 was not greater, so we'll start looking for a pair in the next loop.
lastTimeD1WasGreater = false;
}
}
}发布于 2018-10-17 19:17:56
这样做(将以下内容视为伪代码):
public static int[] Dice() {
int[] diceThrownTwoTimes = new int[2];
diceThrownTwoTimes[0] = (int)(Math.random() * 6.0) + 1;
diceThrownTwoTimes[1] = (int)(Math.random() * 6.0) + 1;
return diceThrownTwoTimes;
}
public static void main(String[] args) {
int trials = 0;
for (int i = 0; i < 100000; i++) {
int[] d1 = Dice();
int[] d2 = Dice();
if (d1[0] > d2[0] && d1[1] > d2[1]) {
trials++;
}
}
System.out.println(trials);
}编辑:
要获得dice1值比dice2值连续两次大的尝试,可以执行以下操作:
public static int[] Dice() {
int[] diceThrownTwoTimes = new int[2];
diceThrownTwoTimes[0] = (int)(Math.random() * 6.0) + 1;
diceThrownTwoTimes[1] = (int)(Math.random() * 6.0) + 1;
return diceThrownTwoTimes;
}
public static void main(String[] args) {
int trials = 0;
for (int i = 0; i < 100000; i++) {
int[] d1 = Dice();
int[] d2 = Dice();
if (d1[0] > d2[0] && d1[1] > d2[1]) {
break;
}else{
trials++;
}
}
System.out.println(trials);
}发布于 2018-10-17 19:23:22
我会和
public static int Dice() {
return (int)(Math.random() * 6.0) + 1;
}
public static void main(String[] args) {
int trials = 0;
int count = 0;
while (count < 2) {
int d1 = Dice();
int d2 = Dice();
if (d1 > d2) {
++count;
} else {
count = 0;
}
++trials;
}
println("It took " + trials + " trials for d1 to be larger than d2 " + count + " times in a row.")
}https://stackoverflow.com/questions/52862031
复制相似问题