Java在两个给定值之间生成随机数
我想知道如何在两个给定值之间生成一个随机数。Java在两个给定值之间生成随机数
我能够产生具有以下的随机数:
Random r = new Random();
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
a[i][j] = r.nextInt();
}
}
但是,我怎么能生成0和100(含)之间的随机数?
谢谢大家。
您可以使用例如r.nextInt(101)
对于一个更通用的 “在数量上二者之间” 使用:
Random r = new Random();
int Low = 10;
int High = 100;
int Result = r.nextInt(High-Low) + Low;
这给你一个随机数在10(含)和100(独家)
呃......
int Random = (int)(Math.random()*100);
如果你需要生成一个以上的值,那么就使用 for循环为
for (int i = 1; i <= 10 ; i++)
{
int Random = (int)(Math.random()*100);
System.out.println(Random);
}
如果你想指定一个更像样的范围,比如从10到100(都是ar在范围E)
这样的代码将是:
int Random =10 + (int)(Math.random()*(91));
/* int Random = (min.value) + (int)(Math.random()* (Max - Min + 1));
*Where min is the smallest value You want to be the smallest number possible to
generate and Max is the biggest possible number to generate*/
Java没有两个值之间的随机数发生器在同样的方式,Python做。它实际上只需要一个值来生成随机数。那么你需要做的是给生成的数字添加一个一定的数字,这将导致数字在一个范围内。例如:
package RandGen;
import java.util.Random;
public class RandGen {
public static Random numGen =new Random();
public static int RandNum(){
int rand = Math.abs((100)+numGen.nextInt(100));
return rand;
}
public static void main(String[]Args){
System.out.println(RandNum());
}
}
这个程序的功能完全位于6号线(带有开始“INT兰特......”请注意,Math.abs()只是将数转换为绝对值。 ,并且它被声明为一个int,这并不重要,第一个(100)是我加入随机数字的数字,这意味着新的输出数字将是随机数字+100。numGen.nextInt()是随机数本身的值,因为我把(100)放在它的圆括号里,它是1到100之间的任何数字。所以当我加上100时,它就成为101和200之间的数字。你实际上并不生成数字介于100和200之间,则您将添加到1和100之间的数字。
也可以尝试以下:
public class RandomInt {
public static void main(String[] args) {
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
double Random;
if (n1 != n2)
{
if (n1 > n2)
{
Random = n2 + (Math.random() * (n1 - n2));
System.out.println("Your random number is: " + Random);
}
else
{
Random = n1 + (Math.random() * (n2 - n1));
System.out.println("Your random number is: " +Random);
}
} else {
System.out.println("Please provide valid Range " +n1+ " " +n2+ " are equal numbers.");
}
}
}
假设上层是上限和更低的下限,那么你可以做一个随机数R,这两个界限之间有:
int r = (int) (Math.random() * (upper - lower)) + lower;
这是排除在上面 – Rizon 2016-11-15 21:52:42
int r =(Math.random()*(upper-lower))+ lower;它将包容性较低。这可能会有所帮助。 – 2016-11-22 18:59:06
这样,
Random random = new Random();
int randomNumber = random.nextInt(upperBound - lowerBound) + lowerBound;
谢谢你 - 我已经试过了,但它似乎并没有工作。我使用从0到100(含)的随机数来填充多维数组;当尝试它时,它会以极大和极小的数字填充数组。例如,-3.76556749E8 3.0207573E8 2.033182079E9 -6.86227134E8。 – MusTheDataGuy 2011-03-11 10:19:11
显示其余的代码。什么是'了'。 – Erik 2011-03-11 10:20:39
谢谢,我已经设法让这个工作现在。非常感谢! – MusTheDataGuy 2011-03-11 10:21:27