平均随机整数

时间:2014-02-19 15:54:33

标签: java random while-loop

我正在尝试编写一个以整数作为命令行参数的程序,使用random来打印0到1之间的N个均匀随机值,然后打印它们的平均值。

我不确定在while循环中放入什么参数以便随机整数重复n次,n是来自用户的数字,表示随机生成的整数数量

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:0)

如果您只需要执行特定次数的循环,我会使用for循环

以下循环将完全迭代n次,这是我个人在需要完成n次时所使用的内容。

for(int i=0; i<n; i++)
{
    //insert body here
}

答案 1 :(得分:0)

int total = 0;
for (int current = 1; current <= n; n++) {
    double rand = Math.random();
    total += rand;
    System.out.println(currentN + "= " + rand);
}
System.out.println("Total = " + total);

答案 2 :(得分:0)

假设您的PRNG表现得恰到好处,您只需要这样:

main()
{
   printf("\n0.5");
   exit(0);
}

对于足够大的N来说......在恒定时间内计算。否则使用移动平均公式:

http://en.wikipedia.org/wiki/Moving_average

只需要O(1)存储空间而不是简单的O(N)方法

这里剪切和粘贴java代码:

public class Rolling {

    private int size;
    private double total = 0d;
    private int index = 0;
    private double samples[];

    public Rolling(int size) {
        this.size = size;
        samples = new double[size];
        for (int i = 0; i < size; i++) samples[i] = 0d;
    }

    public void add(double x) {
        total -= samples[index];
        samples[index] = x;
        total += x;
        if (++index == size) index = 0; // cheaper than modulus
    }

    public double getAverage() {
        return total / size;
    }   
}
相关问题