简体   繁体   English

在Java中生成随机数?

[英]Generating random numbers in Java?

I would like to ask how to make a program that needs using a loop to generate 100 different numbers from 200 to 500 and then multiply them all together. 我想问一下如何制作一个需要使用循环来生成200到500之间的100个不同数字,然后将它们全部相乘的程序。 The result should be printed on the console. 结果应打印在控制台上。 I don't know how to multiply all numbers together. 我不知道如何将所有数字相乘。

This is what I did so far: 这是我到目前为止所做的:

import java.util.Random;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        for(int i=0;i<100;i++)
            System.out.println("Random number["+(i+1)+"]:"+(int)(Math.random()*500));
    } 
}

I believe you are looking for something like, 我相信您正在寻找类似的东西,

Random rand = new Random();
BigInteger val = BigInteger.ONE;
for (int i = 0; i < 100; i++) {
    int v = rand.nextInt(301) + 200; // 0-300 + 200, is the range 200-500.
    val = val.multiply(BigInteger.valueOf(v));
    System.out.printf("Random number %d: %d%n", i + 1, v);
}
System.out.println(val);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM