【问题标题】:How to fill an array with random numbers from 0 to 99 using the class Math?如何使用数学类用 0 到 99 的随机数填充数组?
【发布时间】:2014-11-04 06:43:46
【问题描述】:

我写了代码,但是没有从double到int的转换。

public class Array {
    public static void main(String[] args) {
        int i;
        int[] ar1 = new int[100];
        for(int i = 0; i <  ar1.length; i++) {
            ar1[i] = int(Math.random() * 100);
            System.out.print(ar1[i] + "  ");
        }
    }
}

如何纠正?

【问题讨论】:

  • ar1[i] = ((int) Math.random() * 100);
  • 足够智能的 IDE(如 Eclipse 或 IntelliJ)应该能够自行纠正它:(int) (Math.random() * 100);
  • 不是一个答案,正如你所说你必须使用数学,但类 Random 有一个 nextInt() 函数来创建随机整数
  • 你还声明了两次imain() 中的第一行应该被删除。

标签: java arrays random


【解决方案1】:
 ar1[i] = (int)(Math.random() * 100);

Java 中的转换看起来像 C 中的转换。

【讨论】:

  • 而且也叫铸造。
  • 您需要严格执行此操作。
【解决方案2】:

应该是这样的

 ar1[i] = (int)(Math.random() * 100);

当你投射时,投射类型应该在括号中,例如(cast type)value

【讨论】:

  • 您需要严格执行此操作。
【解决方案3】:

试试这个:

package studing;

public class Array {
    public static void main(String[] args) {
        Random r = new Random();
        int[] ar1 = new int[100];
        for(int i = 0; i < ar1.length; i++) {
            ar1[i] = r.nextInt(100);
            System.out.print(ar1[i] + "  ");
        }
    }
}

为什么?

  1. 使用Math.random()可以返回1,这意味着Math.random()*100可以返回100,但是OP要求最大99!使用nextInt(100)是独占100,只能返回0到99之间的值。
  2. Math.random() 无法返回 -0.000001 将舍入为 0 1.0000001 无法返回应舍入为 1。因此,您获得099 的机会少于两者之间的所有数字。这样就不是真的随机了,猜测“它不是099”比“它不是198”更真实。
  3. 此外,它不会通过您并不真正需要的强制转换和数学运算绕道,嘿,您不需要在 amd-cpus 或旧的 intel-cpus 上 strictfp

【讨论】:

    【解决方案4】:

    这实际上并没有使用java.lang.Math 类,但在Java 8 中也可以用这种方式创建一个随机数组:

    int[] random = new Random().ints(100, 0, 100).toArray();

    【讨论】:

      【解决方案5】:

      我的解决方案使用 Random 类而不是 Math.random。这里是。

      private static int[] generateArray(int min, int max) {          // generate a random size array with random numbers
          Random rd = new Random();                                   // random class will be used
          int randomSize = min + rd.nextInt(max);                     // first decide the array size (randomly, of course)
          System.out.println("Random array size: " + randomSize);     
          int[] array = new int[randomSize];                          // create an array of that size
          for (int i = 0; i < randomSize; i++) {                      // iterate over the created array 
              array[i] = min + rd.nextInt(max);                       // fill the cells randomly
          }
          return array;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-23
        • 1970-01-01
        • 2013-09-16
        • 1970-01-01
        • 2013-04-18
        相关资源
        最近更新 更多