for循环控制掷骰子的次数。 (Java)
for-loop controlling the number of times the Dice are rolled. (Java)
我正在制作一个 Java 程序,允许用户输入掷骰子的次数。我使用带有 timesRolled 变量的 for 循环来控制循环程序的次数。我想添加所有随机骰子值以获得总和。
int timesRolled = 4;
int result = 0;
for (int i = 0; i < timesRolled; i++) {
int rand1 = getRandom(1,6); // getrandom is a function withing the template.
result = rand1 ;
outputln(result);
}
您需要在每次迭代中将结果的当前值添加到新确定的骰子值,并将其分配给结果:result = result + rand1
或简称 result += rand1
。同样在for循环中调用outputln(result);
,每次迭代都会输出累计和,所以你可能想把它移出到最后只输出一次。
int timesRolled = 4;
int result = 0;
for (int i = 0; i < timesRolled; i++) {
int rand1 = getRandom(1,6); // getrandom is a function withing the template.
result += rand1 ;
}
outputln(result);
我正在制作一个 Java 程序,允许用户输入掷骰子的次数。我使用带有 timesRolled 变量的 for 循环来控制循环程序的次数。我想添加所有随机骰子值以获得总和。
int timesRolled = 4;
int result = 0;
for (int i = 0; i < timesRolled; i++) {
int rand1 = getRandom(1,6); // getrandom is a function withing the template.
result = rand1 ;
outputln(result);
}
您需要在每次迭代中将结果的当前值添加到新确定的骰子值,并将其分配给结果:result = result + rand1
或简称 result += rand1
。同样在for循环中调用outputln(result);
,每次迭代都会输出累计和,所以你可能想把它移出到最后只输出一次。
int timesRolled = 4;
int result = 0;
for (int i = 0; i < timesRolled; i++) {
int rand1 = getRandom(1,6); // getrandom is a function withing the template.
result += rand1 ;
}
outputln(result);