我有一个可以容纳 5 个整数的数组。在 for 循环中,我使用 Math.random() 用 0 到 10 之间的随机整数值(可以是正数或负数)填充数组。我怎样才能收到负值?有人建议我将公式乘以 -1 以用正值和负值填充数组,但是当我这样做时,数组中的所有值都是负值。我认为问题出在这一行
int r = 0 + (int) (Math.random() * 10 *(-1));
这是代码:
public class Random
{
public static void main(String [] args)
{
int [] arr= new int[5];
for(int k=0; k<arr.length; k++)
{
int r = 0 + (int) (Math.random() * 10 *(-1));
arr[k] = r;
}
int j = 0;
while(i<arr.length) {
System.out.print(arr[i] + " ");
j++;
}
}
}
现在我的输出是-7 -3 -3 -5 -6
我希望我的输出为 7 -3 3 -5 6
最佳答案
如果您想要 -10 到 10 之间的数字:
int r = (int) (Math.random() * 21) - 10;
由于 Math.random()
永远不会返回 1.0,(int) (Math.random() * 21)
将返回 0 到 20 之间的整数,并且在减去之后10、你会得到你想要的。
另一种方法是使用java.util.Random
:
Random rand = new Random();
int r = rand.nextInt(21) - 10;
关于java - 如何获得可以为正值也可以为负值的随机值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25994191/