【问题标题】:Printing Loops of random numbers打印随机数循环
【发布时间】:2014-11-27 20:11:13
【问题描述】:

有人能解释为什么程序 1 重复打印一个随机数吗?而下面的程序 2 打印 100 个随机数?另外,是否要编辑程序 1 来执行程序 2 的操作?

程序 1

public class RandomComparison {

    public static void main(String[] args){

        int rnd = (int) Math.random() * 6 + 1;

        for(int i=0; i<100; i++){
        System.out.print(rnd);
        }

    }


}

程序 2

public class RandomPractice {
    public static void main (String[] args){
        int roll;
        String msg = "Here are 100 random rolls of the dice:";
        System.out.println(msg);

        for (int i=0; i<100; i++){
            roll = randomInt(1, 6);
            System.out.print(roll);
        }
    }

    public static int randomInt(int low, int high){
        int result = (int) (Math.random()*(6) + low);
        return result;
    }
}

【问题讨论】:

  • 因为您正在打印相同的变量rnd

标签: loops random printing numbers


【解决方案1】:

在第一种方法中,您检索一个随机值一次并打印该单个值 100 次。第二种方法是生成一个随机数 100 次,并在每次迭代时打印出来。

int rnd = (int) Math.random() * 6 + 1;//grabbed only once

for(int i=0; i<100; i++){
    System.out.print(rnd);//printing `rnd` 100 times
}



for (int i=0; i<100; i++){
        roll = randomInt(1, 6);//calling for a new random number with each iteration, then printing it
        System.out.print(roll);
}

并正确使用您的randomInt 方法:

public static int randomInt(int low, int high){
    int result = (int) (Math.random()*(high) + low);//replace `6` with the parameter `high`
    return result;
}

修复您的第一种方法,使其运行方式与第二种方法相同:

public class RandomComparison {

   public static void main(String[] args){

       for(int i=0; i<100; i++){
           System.out.print((int)(Math.random()* 6) + 1);//prints out a random number with every iteration
       }
   }
}

【讨论】:

  • 谢谢你,这很有意义。我如何让它做 rnd 100 次?我试图在循环内移动初始化语句,但我仍然只得到 1 个重复 100 次的数字
  • 你问的是如何生成一个随机数100次并打印每个随机数?如果是这样,上面代码中的第二个 for 循环以及您的 randomInt 方法可以完成此操作。你只需要正确使用你的方法参数。我会把这个放在我的答案中。
  • 第一个问题是。我只是想知道除了创建另一个类之外,是否还有另一种方法可以生成 100 次随机数。我觉得有比必须这样做更简单的方法。
  • 您的意思是创建两个程序来尝试完成相同的壮举吗?或者第二种方法 - 在这种情况下randomInt()?
  • 我现在明白我的错误了。非常感谢!我现在明白了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 2015-01-03
  • 2013-10-24
相关资源
最近更新 更多