如何生成随机整数?

huangapple go评论63阅读模式
英文:

How do I make a random int?

问题

这里是您的翻译代码部分:

for (i = 1; i <= 100; i++) {
    int r = (int) (Math.random() * 100) + 1;
    System.out.print(r + ", ");
}

请注意,我只进行了代码的翻译,不包括额外的解释或回答。如果您有任何其他问题或需要进一步的帮助,请随时提问。

英文:

So I am trying to make 100 random integers from 1-100 print out. I can make doubles of this but not integers. Please show me how to make this into integers, here is the code.

for(i = 1; i &lt;= 100; i++) {
    double r = Math.random();
    double in = r * 100;
    System.out.print(in + &quot;, &quot;);
}  

Please show me what I messed up or if I need to use an alternate technique for this

答案1

得分: 1

你可以使用 Java.util 包中的 Random 对象替代。

Random random = new Random();
int value = random.nextInt(100);
英文:

You can use Random object instead. from java.util package

Random random = new Random();
int value = random.nextInt(100);

答案2

得分: -1

使用ThreadLocalRandom:

for (int i = 1; i <= 100; i++) {
    System.out.print(ThreadLocalRandom.current().nextInt(100) + ", ");
}
英文:

Use ThreadLocalRandom:

        for (int i = 1; i &lt;= 100; i++) {
            System.out.print(ThreadLocalRandom.current().nextInt(100) + &quot;, &quot;);
        }

答案3

得分: -1

导入类 java.util.Random
创建类 Random 的实例,即 Random rand = new Random()
调用 rand 对象的以下方法之一:
nextInt(upperbound) 生成范围在 0 到 upperbound-1 之间的随机数。
nextFloat() 生成介于 0.0 和 1.0 之间的浮点数。
nextDouble() 生成介于 0.0 和 1.0 之间的双精度浮点数

例如,如果您想生成一个介于 1 到 100 之间的随机数,则代码将如下所示。

import java.util.Random;
Random r = new Random();
int number = r.nextInt(100);

因此,变量 number 将是一个介于 1 到 100 之间的随机数。

英文:

Import the class java.util.Random
Make the instance of the class Random, i.e., Random rand = new Random()
Invoke one of the following methods of rand object:
nextInt(upperbound) generates random numbers in the range 0 to upperbound-1.
nextFloat() generates a float between 0.0 and 1.0.
nextDouble() generates a double between 0.0 and 1.0

For example if you want to generate a random number between 1 to 100 the the code will be.

import java.util.Random;
Random  r = new Random();
Int number = r.nextInt(100);

So variable number will be a random number between 1 to 100

答案4

得分: -2

以下是翻译好的内容:

错误的是语句 double in = r * 100;
必须是

 int b = (int) (Math.random()*100)%100; //范围 [0-99]

如果您严格希望 b 在范围 [1-100],只需将 b 增加 1。

英文:

Whats wrong is the statement double in = r * 100;
It must be

 int b = (int) (Math.random()*100)%100; //range [0-99]

Just add 1 to b if you strictly want b in the range [1-100]

huangapple
  • 本文由 发表于 2020年10月3日 23:32:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/64185910.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定