从大小为 10 的数组中生成 1000 个随机数并找到数字的平均值并将它们打印在屏幕上 [重复]

Posted

技术标签:

【中文标题】从大小为 10 的数组中生成 1000 个随机数并找到数字的平均值并将它们打印在屏幕上 [重复]【英文标题】:generate 1000 random numbers from size 10 array and find the average of the numbers and print them on the screen [duplicate] 【发布时间】:2017-04-21 05:51:42 【问题描述】:
import java.util.Random;
public class exam1

    public static void main (String args[])
    
    //  Scanner scan = new Scanner(System.in);
        int array [] = new int[10];
        Random rand = new Random(1001);
        int sum = 0;
        int sum1 = 0;

        for(int i=0; i<array.length; i++)
        
            array[i]=rand;
            sum = sum+array[i];
            sum1=sum/array.length;
        
            System.out.println(sum);
    

我根本无法生成随机数。如何从大小为 10 的数组中生成 1000 个随机数并求出这些数字的平均值并打印在屏幕上?

【问题讨论】:

你需要调用RandomnextInt()方法。 rand.nextint() 去哪里了 【参考方案1】:
 import java.util.Random;
public class exam1

    public static void main (String args[])
    
    //  Scanner scan = new Scanner(System.in);
        int array [] = new int[10];
        Random rand = new Random();
        int sum = 0;
        int sum1 = 0;

        for(int i=0; i<array.length; i++)
        
            array[i]=rand.nextInt(1001);
            sum = sum+array[i];
            sum1=sum/array.length;
        
            System.out.println(sum1);
    


我认为这很有效

【讨论】:

【参考方案2】:

试试这个:

    import java.util.Random;
    public class exam1
    
    public static void main (String args[])
    
    //  Scanner scan = new    Scanner(System.in);
        int array [] = new int[10];
        Random rand = new Random();
        //You could use just one variable
        int sum = 0;

        for(int i=0; i<array.length; i++)
        
    //Generate random integer between 0 and 1000
            array[i]=rand.next(1000);
            sum = sum+array[i];
            sum=sum/array.length;
        
            System.out.println(sum);
    


【讨论】:

以上是关于从大小为 10 的数组中生成 1000 个随机数并找到数字的平均值并将它们打印在屏幕上 [重复]的主要内容,如果未能解决你的问题,请参考以下文章