java - 如何获得可以为正值也可以为负值的随机值?

标签 java arrays loops for-loop

我有一个可以容纳 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/

相关文章:

java - 在类之间传递有意义的消息的方法?

java - Eclipse 说我缺少 Red5 插件的类路径条目 red5.jar

c - 将输入文本读入单词数组并去掉标点符号

javascript - 获取数组的子项数

javascript - 一次对数组的所有值使用 .addEventListener

css - 在 SCSS 中使用 Dot Before Var

java - Spring Webflux : Extract a value from a Mono and save it into another variable

java - Hybris 重新声明关系

python - 有没有办法可以为列表中的同一个团队加分?

java - 将伪代码转换为尽可能相似的实现