【发布时间】:2013-12-16 13:03:13
【问题描述】:
我正在尝试从 C 中的数组中选择随机索引。The problem I'm having is that my random numbers aren't going from the range I expect (from 0 to 2047) as this example says that it will。仅仅从我得到的索引来看,我似乎得到了 1000-1200 之间的数字,而不是所需的范围。
这是调用 rand() 的代码。
#define MAXPAGES 2048 // maximum number of processes in the system
//until we have a node, pick random indexes.
while(node == NULL){
table_index = rand() % MAXPAGES;
node = table[table_index];
if(node){
fprintf(stderr, "%d\n", table_index);
if(node->current_pages > 0) break;
else node = NULL;
}
}
我在 main 函数中只调用了一次 srand。
int main(int argc, char** argv) {
int i;
int simulations = 100000;
// initialize the process hash table
if(argc > 1){
removal_algorithm = atoi(argv[1]);
if(argc == 3) simulations = atoi(argv[2]);
}
srand(time(NULL));
for (i = 0; i < MAXPAGES; i++) table[i] = NULL;
printf("Random replacement MMU simulation on %d simulations started\n", simulations);
Simulate(simulations);
printf("Random MMU simulation completed. only writing page faults:,");
printf("%d, read / write page faults: %d, total page faults: %d\n", read_miss, write_miss, read_miss + write_miss);
}
示例序列。
1117
1069
1103
1118
1071
1117
1120
1092
1099
1116
1121
1122
1110
1116
1069
1113
1120
1117
1116
1071
1121
1094
1110
1119
1102
1117
1071
1108
1102
1099
1109
1109
1092
1109
1120
1108
1094
1101
1122
1086
1110
1108
1119
1120
1092
1113
1117
1121
【问题讨论】:
-
这似乎不是问题所在,但请注意,
rand() % SOME_VALUE可能会因RAND_MAX和SOME_VALUE的值而产生很大偏差。如果RAND_MAX不是是SOME_VALUE的倍数,请考虑生成的分布。 -
如何在不使用 mod 运算符的情况下获得随机范围?
-
值得一读In C, how do I get a specific range of numbers from rand()?的所有答案和cmets