我很难搞清楚如何让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 1 1 1 2 4 4 4 3 3 4 3 3 4 4 5 5 5 4 4 5 6 6 6 7 7 7 6 6 6 7 7 7 6 6 6 7 7 7 8 8 8 9 8 8 8 9 9 9
最后的职位是: 10
已采取的步骤数目为: 58
有21个零。(出现错误的地方)
发布于 2016-10-26 15:45:58
如果该职位实际上在0,请确保您正在递增该职位。而且,没有必要在每次行走的迭代中生成两个随机数。
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." );
}https://stackoverflow.com/questions/40266538
复制相似问题