【问题标题】:How to get the random value that can be positive or negative? [duplicate]如何获得可以是正数或负数的随机值? [复制]
【发布时间】:2014-09-23 11:41:13
【问题描述】:

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

【问题讨论】:

  • 尝试arr[k] = r * ((Math.random() &gt; 0.5) ? 1 : -1) 将随机添加到负/正。或者您可以移动随机区间的范围(Eran 的回答)

标签: java arrays loops for-loop


【解决方案1】:

如果你想要介于 -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;

【讨论】:

  • 可能应该使用 Math.round 而不是总是向下舍入(转换为 int)
【解决方案2】:

您可以生成一个介于 0 到 20 之间的随机数并从中减去 10。这样做你会得到一个介于 -10 和 +10 之间的随机数:

int r = (int) ( Math.random() * 20 ) - 10;

【讨论】:

    【解决方案3】:

    你只需要修改你的代码如下

        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*(k % 2 == 0? 1:-1));
                    arr[k] = r;
                }
                int j = 0;
                while(j<arr.length)
                {
                    System.out.print(arr[j]+ " ");
                    j++;
    
                }
                System.out.println();
            }
    
        }
    

    【讨论】:

      猜你喜欢
      • 2015-03-14
      • 2019-10-21
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      • 1970-01-01
      • 2023-03-27
      相关资源
      最近更新 更多