【问题标题】:Java Random number between -100 and 100Java 随机数介于 -100 和 100 之间
【发布时间】:2014-03-19 23:23:20
【问题描述】:

我创建了这个程序来打印 -100 到 100 之间的数字,但我想知道这是正确的方法还是必须在限制(预先指定)a 和 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);
       }


}

}

【问题讨论】:

  • 前10个数字将从-100到0,后10个从0到100。
  • 非常常见的问题。请参阅此线程以生成范围内的数字。 stackoverflow.com/questions/363681/…
  • 你不应该将变量名大写,否则有人可能会将它们误认为是一个类!至于您的问题,您可以简单地使用Random rand = new Random();int n = rand.nextInt()%101; @JBueno 提到的链接解释了您需要的一切。

标签: java math utilities


【解决方案1】:

如果要生成介于 -100 和 100 之间的数字:

public class RandomNumber {


public static void main (String [] args){


     for (int i = 1; i <= 10 ; i++)
       {
        int Random = (int)(Math.random()*(200 + 1)) - 100;
        System.out.println(Random);
       }


    }
}

这是因为Math.random() 生成一个介于01 之间的值。然后将该值乘以 200 并减去 100。

例子:

((0.75) * (200 + 1)) - 100 = 150 - 100 = 50

如果您想要一个介于 a(较小)和 b(较大)之间的数字,请尝试:

int Random = (int)(Math.random() * (b - a + 1)) + a;

示例 (a = 30, b = 70):

Random = 0
(0)(70 - 30 + 1) + 30 = 0 + 30 = 30

Random = 0.5
(0.5)(70 - 30 + 1) + 30 = 20 + 30 = 50

Random = 1
(0.999999)(70 - 30 + 1) + 30 = 40 + 30 = 70

【讨论】:

  • @user3421469 我在答案中添加了相关信息。
  • 不,这是不正确的。将 double 或 float 转换为 int 总是向零舍入。所以这将产生一个从 -99 到 100 的数字,其中 0 的可能性是其他数字的两倍。
  • @DavidWallace 你能解释一下为什么吗?我不完全明白。
  • 嗯,它通过将一个介于 -100 和 +100 之间(不包括在内)的 double 转换为 int 来工作。所以它产生的最小数字是(int)(-99.9999....),即-99,它产生的最大数字是(int)(99.999999....),即99。此外,如果它开始的double在-1和1之间,不包括在内,它会被强制转换为 0。所以它是 0 的可能性是其他任何东西的两倍,它永远不会是 -100 或 100。在我之前的评论中,我没有看到你也忘记了其他的 +1包括受访者。
  • 我刚刚使用了我对你的函数的回答中的测试应用程序(只需将getRandomIntBetween 的正文更改为你的:return (int)((Math.random()*(max-min))+min);)。它证实了@DavidWallace 所说的一切。
【解决方案2】:

拥有一个可以重复使用的更通用的函数总是很好的:

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));
    }
}

【讨论】:

  • 不,这是不正确的。将 double 或 float 转换为 int 总是向零舍入。所以这将产生一个从 -99 到 100 的数字,其中 0 的可能性是其他数字的两倍。
  • 你是对的。我通过在投射后添加a 来修复它。
  • 是的,现在看起来好多了。
【解决方案3】:

最好的办法是

Random r = new Random();
int n = -100 + (int)(r.nextFloat() * 200);

因为您要移动的范围是 200 个单位。 nextFloat 将返回一个介于 0.0 和 1.0 之间的值,然后乘以 200 并减去 100 和 BAM! -100 到 100!

【讨论】:

  • 不,这是不正确的。将 double 或 float 转换为 int 总是向零舍入。所以这将产生一个从 -99 到 100 的数字,其中 0 的可能性是其他数字的两倍。
  • 对!所以让我提供正确的演员阵容!
【解决方案4】:

我认为这是最简单的:

public static final int getRandomBetweenInclusive(int min, int max)  {
   return  (min + (int)(Math.random() * ((max - min) + 1)));
}

调用它

int random = RandomNumberUtil.getRandomBetweenInclusive(-100, 100);

它实际上来自this answer。它真的很聪明,简洁。


我编写了这个测试应用程序来确认它平均分配了所有可能性:

  import  java.util.Iterator;
  import  java.util.TreeMap;
  import  java.util.Map;
  import  java.util.List;
  import  java.util.ArrayList;
/**
   <P>{@code java RandomNumberTest}</P>
 **/
public class RandomNumberTest  {
  private static final int tryCount = 1_000_000;
   public static final void main(String[] ignored)  {

     Map<Integer,Integer> randCountMap = new TreeMap<Integer,Integer>();
     for(int i = 0; i < tryCount; i++)  {
        int rand = getRandomBetweenInclusive(-10, 10);
        int value = ((!randCountMap.containsKey(rand)) ? 1
           :  randCountMap.get(rand) + 1);
        randCountMap.put(rand, value);
     }

     Iterator<Integer> allIntItr = randCountMap.keySet().iterator();

     List<NumWithCount> numWcountList = new ArrayList<NumWithCount>(randCountMap.size());

     while(allIntItr.hasNext())  {
        Integer I = allIntItr.next();
        int count = randCountMap.get(I);
        NumWithCount nwc = new NumWithCount(I, count);
        numWcountList.add(nwc);
     }

     Iterator<NumWithCount> intWCountItr = numWcountList.iterator();
     while(intWCountItr.hasNext())  {
        NumWithCount numWCount = intWCountItr.next();
        float pct = (float)numWCount.occurances  / tryCount * 100;
        System.out.println(numWCount.num + ": " + numWCount.occurances + "   " + String.format("%.3f", pct) + "%");
     }
   }
   public static final int getRandomBetweenInclusive(int min, int max)  {
     return  (min + (int)(Math.random() * ((max - min) + 1)));
   }
}
class NumWithCount  {
   public final int num;
   public final int occurances;
   public NumWithCount(int num, int occurances)  {
      this.num = num;
      this.occurances = occurances;
   }
   public String toString()  {
      return  "num=" + num + ", occurances=" + occurances;
   }
}

输出:

[R:\jeffy\programming\sandbox\xbnjava]java RandomNumberTest 1000000
-10: 47622   4.762%
-9:  48024   4.802%
-8:  47579   4.758%
-7:  47598   4.760%
-6:  47660   4.766%
-5:  47299   4.730%
-4:  47635   4.764%
-3:  47675   4.767%
-2:  47678   4.768%
-1:  47757   4.776%
 0:  47557   4.756%
 1:  47888   4.789%
 2:  47644   4.764%
 3:  47177   4.718%
 4:  47381   4.738%
 5:  47836   4.784%
 6:  47539   4.754%
 7:  47561   4.756%
 8:  47520   4.752%
 9:  47481   4.748%
 10: 47889   4.789%

【讨论】:

  • +1。这是目前这里唯一正确的答案。请接受我几分钟前误读的道歉。
  • 答案已更新。抱歉,我的反驳太过分了,无法停止:)
【解决方案5】:

这真的取决于你想要实现什么。如果你想在同一个循环中打印 -100 到 +100 之间的数字,你可以这样做:

 for (int i = 1; i <= 10 ; i++)
   {
    int random = (int)(Math.random()*200-100);
    System.out.println(random);
   }

【讨论】:

  • 不,这是不正确的。将 double 或 float 转换为 int 总是向零舍入。所以这将产生一个从 -99 到 100 的数字,其中 0 的可能性是其他数字的两倍。
  • 抱歉,-99 到 99。它永远不会产生 -100 或 100。
猜你喜欢
  • 2012-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-18
  • 1970-01-01
  • 2011-01-23
相关资源
最近更新 更多