【问题标题】:How do I make these values both positive and negative?如何使这些值既积极又消极?
【发布时间】:2014-09-23 21:27:48
【问题描述】:

如何让这个程序打印出负值和正值,这样就会有从 -100 到 100 的随机数?

public class RandomInts {

    /* 
     * This program makes 10 random integers and prints them out on the console window.
     */
    public static void main(String[] args) {
        int[] myArray;      
        myArray = new int[10];

        for( int i = 0; i < myArray.length; i++ ){
            myArray[i] = (int)(Math.random() * 100);
        } // End of first for loop.

        for(int i=0;i<10;i++){
            System.out.println("My array is " + myArray[i]);
        } // End of second for loop.

    } // End of the main.

} // End of the class RandomInts.

【问题讨论】:

  • 生成0到200之间的随机数,减去100。
  • 因为Math.random() &lt; 1(int)(Math.random() * 100) 永远不会得到 100
  • 看看stackoverflow.com/questions/5271598/…,这基本上是 JB Nizet 所解释的。

标签: java for-loop random


【解决方案1】:

你可以试试——

公共类 RandomInts {

/* 
 * This program makes 10 random integers and prints them out on the console window.
 */
public static void main(String[] args) {
    int[] myArray;      
    myArray = new int[10];

    for( int i = 0; i < myArray.length; i++ ){
        myArray[i] = (int)(Math.random() * 200) - 100;
    } // End of first for loop.

    for(int i=0;i<10;i++){
        System.out.println("My array is " + myArray[i]);
    } // End of second for loop.

} // End of the main.

} // RandomInts 类结束。

【讨论】:

    【解决方案2】:

    myArray[i] = r.nextInt() % 101Random r = new Random() 怎么样

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      • 1970-01-01
      • 2019-03-13
      • 2020-06-11
      • 2022-08-08
      • 1970-01-01
      相关资源
      最近更新 更多