首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java:随机生成的Zeroes数

Java:随机生成的Zeroes数
EN

Stack Overflow用户
提问于 2016-10-26 15:38:33
回答 1查看 77关注 0票数 1

我很难搞清楚如何让Java在随机生成的数字列表中计算零的数量,直到达到"-10“或”+10“为止。

我很感激你的帮助,

谢谢。

我的守则:

代码语言:javascript
复制
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个零。(出现错误的地方)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-26 15:45:58

如果该职位实际上在0,请确保您正在递增该职位。而且,没有必要在每次行走的迭代中生成两个随机数。

代码语言:javascript
复制
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." );
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40266538

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档