【发布时间】:2017-11-09 07:28:12
【问题描述】:
我正在生成 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
【问题讨论】:
-
这是很多代码。你能把问题缩小到几行代码吗?
-
当然,我刚刚因为没有完全可编译的代码而被标记,所以我很安全。
-
这是一个微妙的平衡。你想给我们可编译的代码,但又不想让我们不得不去寻找问题。
-
确实如此。虽然对于使用随机数太久的老猫来说,它就像拇指酸痛一样。
-
我已经编辑了要精简的问题,但是我认为我的输出现在不太有意义了,所以如果有任何混淆,请告诉我。