Java:随机生成的零的数量
我很难准确地计算出如何让Java计算随机生成的数字列表中的零数量,直到它达到“-10”或“+10” 我非常感谢你的帮助 多谢各位 我的代码:Java:随机生成的零的数量,java,if-statement,while-loop,count,whitespace,Java,If Statement,While Loop,Count,Whitespace,我很难准确地计算出如何让Java计算随机生成的数字列表中的零数量,直到它达到“-10”或“+10” 我非常感谢你的帮助 多谢各位 我的代码: import java.util.Random; public class RandomWalk { public static void main(String[] args) { Random rand = new Random(); int position = 0; int s
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." );
}
}
import java.util.Random;
公共课随机化步行
{
公共静态void main(字符串[]args)
{
Random rand=新的Random();
int位置=0;
int-stepsTotal=0;
int zeroesTotal=0;
while(位置!=10&&position!=-10){
if(rand.nextDouble()<0.5){
位置--;
}
if(rand.nextDouble()<0.5){
位置++;
}
否则{
zeroesTotal++;
}
stepsTotal++;
系统输出打印(“+位置);
}
System.out.println();
System.out.println(“最终位置为:“+位置”);
System.out.println(“采取的步骤数为:“+stepsTotal”);
System.out.println(“有”+zerostotal+zeroes.”);
}
}
示例输出:(我数4个零,不是21个。)(它算什么?)
0 0 0 1 2 3 4 4 4 3 4 4 4 4 4 4 4 6 6 5 6 7 7 7 7 8 8 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." );
}
publicstaticvoidmain(字符串[]args)
{
Random rand=新的Random();
int位置=0;
int-stepsTotal=0;
int zeroesTotal=0;
while(位置!=-10&&position!=10){
if(rand.nextDouble()<0.5){
位置--;
}
否则{
位置++;
}
如果(位置==0){
zeroesTotal++;
}
stepsTotal++;
系统输出打印(“+位置);
}
System.out.println();
System.out.println(“最终位置为:“+位置”);
System.out.println(“采取的步骤数为:“+stepsTotal”);
System.out.println(“有”+zerostotal+zeroes.”);
}
在我看来,您的代码所做的事情与您的问题陈述并不相似:“我很难准确地计算出如何让Java计算随机生成的数字列表中的零数量,直到达到“-10”或“+10”请修改-您希望在输出中看到什么?我希望看到“有x个零”。上面输出的零数量正确。添加了说明。