Java随机数介于-100和100之间 [英] Java Random number between -100 and 100
本文介绍了Java随机数介于-100和100之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经创建了该程序来打印-100到100之间的数字,但是我想知道这是否是正确的方法,还是必须在限制a(和b)之间进行?
I have created this program to print numbers between -100 and 100 but I am wondering if this is the right way to do it or it has to be done between limits (pre-specified) a and b?
public class RandomNumber {
public static void main (String [] args){
for (int i = 1; i <= 10 ; i++)
{
int Random = (int)(Math.random()*-100);
System.out.println(Random);
}
for (int i = 1; i <= 10 ; i++)
{
int Random1 = (int)(Math.random()*100);
System.out.println(Random1);
}
}
}
推荐答案
拥有更通用的函数可以重复使用总是很高兴的:
It's always nice to have a more general function which you can reuse:
private static int getRandomNumber(int a, int b) {
if (b < a)
return getRandomNumber(b, a);
return a + (int) ((1 + b - a) * Math.random());
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.format("%d ", getRandomNumber(-100, 100));
}
}
这篇关于Java随机数介于-100和100之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文