为什么rand()给出了我定义的间隔之外的数字? (昨天工作正常)

时间:2017-06-07 19:23:26

标签: c++ random ctime

我生成1000和11000之间的随机整数。但是它们必须具有6000的平均值。我昨天在我的程序中使用了这段代码并且它运行得很好,但现在它给了我很大的数字,好像我的间隔没关系。

编辑:将代码删除一点以便于阅读。

srand(time(NULL));
int k = 5;
int cTotal = 0;
int cAverage = 0;

  struct process {
    int pid; // process id
    int cycles; // number of cycles required to complete the process
    int mSize; // size of the memory footprint
};

    for (int i = 0; i < k; i++) {

        processes[i].pid = i; // set the unique identifier of the process.

        // If statements for determining the number cycles in each process
        if (k == 0) {
            processes[i].cycles = 6000; // if the user decides to try only one process, the average must be 6000, so assign 6000 as its value.
            cTotal += processes[i].cycles; //update the total number of cycles, and the average.
            cAverage = cTotal / (i + 1);

        } else if (cAverage == 0) { // if we have more than 1 process and  it happens to be the first one, go ahead and randomize it since we can adjust the average after the first iteration.
            processes[i].cycles = rand() % 11000 + 1000; //update the total number of cycles, and the average.
            cTotal += processes[i].cycles;
            cAverage = cTotal / (i + 1);

        } else if (cAverage == 6000 && i != k - 1) { // if the average is already at 6000, it's safe to choose any random number so do that unless this is the last iteration of the loop.
            processes[i].cycles = rand() % 11000 + 1000; //update the total number of cycles, and the average.
            cTotal += processes[i].cycles;
            cAverage = cTotal / (i + 1);

        } else {
            processes[i].cycles = (6000 * (i + 1)) - cTotal; // set the number of cycles such that the average will be 6000
            cTotal = cTotal + processes[i].cycles; //update the total number of cycles, and the average.
            cAverage = cTotal / (i + 1);
        }
    } //for

Edit2:这是我程序的一些输出(包括这个加上另一个相同的内存大小if语句)

    How many processes would you like to simulate? - >5
  5
Simulating 5 Processes...
***********************
PID: 0
Cycles: 63
Mem Size: 1877994624
***********************
PID: 1
Cycles: -23
Mem Size: 1877936645
***********************
PID: 2
Cycles: -1877936648
Mem Size: 13
***********************
PID: 3
Cycles: -1877936641
Mem Size: 64
***********************
PID: 4
Cycles: -1877936685
Mem Size: 4201340
***********************
Total Cycles: 30000
Average Cycles: 6000
Average Memory: 376427625 KB

1 个答案:

答案 0 :(得分:7)

你的范围需要rand()%10000 + 1000。

将昨天归结为统计异常。

有更好的方法(这种方法对较低的数字有统计偏差)。查看std :: uniform_int_distribution,并考虑使用Mersenne Twister作为实际生成器。