我无法弄清楚如何让 Java 计算随机生成的数字列表中零的数量,直到它达到“-10”或“+10”。
如果有任何帮助,我将不胜感激
谢谢。
我的代码:
import java.util.Random;
public class RandomWalk
{
public static void main(String[] args)
{
Random rand = new Random();
int position = 0;
int stepsTotal = 0;
int zeroesTotal = 0;
while (position !=10 && position != -10) {
if (rand.nextDouble() < 0.5) {
position--;
}
if (rand.nextDouble() < 0.5) {
position++;
}
else {
zeroesTotal++ ;
}
stepsTotal++;
System.out.print(" " + position);
}
System.out.println();
System.out.println("The final position is: " + position);
System.out.println("The number of steps taken is: " + stepsTotal);
System.out.println("There are " + zeroesTotal + " zeroes." );
}
}
示例输出:(我数了 4 个零,而不是 21 个。)(它算的是什么?)
0 0 0 0 1 1 2 3 4 4 4 3 3 4 3 4 3 4 4 5 5 4 4 5 6 6 6 6 5 5 6 7 8 7 7 7 6 6 6 6 7 7 7 7 8 8 8 9 8 9 9 8 7 8 9 9 9 10
最后的位置是:10
所走的步数是:58
有 21 个零。 (哪里出错了)
最佳答案
如果位置实际上在 0
,请确保您递增 zeroesTotal
。此外,无需在每次步行迭代中生成两个随机数。
public static void main(String[] args)
{
Random rand = new Random();
int position = 0;
int stepsTotal = 0;
int zeroesTotal = 0;
while (position != -10 && position != 10) {
if (rand.nextDouble() < 0.5) {
position--;
}
else {
position++;
}
if (position == 0) {
zeroesTotal++;
}
stepsTotal++;
System.out.print(" " + position);
}
System.out.println();
System.out.println("The final position is: " + position);
System.out.println("The number of steps taken is: " + stepsTotal);
System.out.println("There are " + zeroesTotal + " zeroes." );
}
关于Java:随机生成的零数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40266538/