我想做的是生成一些随机数(不一定是个位数),例如
29106
7438
5646
4487
9374
28671
92
13941
25226
10076
然后计算我得到的位数:
count[0] = 3 Percentage = 6.82
count[1] = 5 Percentage = 11.36
count[2] = 6 Percentage = 13.64
count[3] = 3 Percentage = 6.82
count[4] = 6 Percentage = 13.64
count[5] = 2 Percentage = 4.55
count[6] = 7 Percentage = 15.91
count[7] = 5 Percentage = 11.36
count[8] = 3 Percentage = 6.82
count[9] = 4 Percentage = 9.09
这是我正在使用的代码:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
int i;
srand(time(NULL));
FILE* fp = fopen("random.txt", "w");
// for(i = 0; i < 10; i++)
for(i = 0; i < 1000000; i++)
fprintf(fp, "%d\n", rand());
fclose(fp);
int dummy;
long count[10] = {0,0,0,0,0,0,0,0,0,0};
fp = fopen("random.txt", "r");
while(!feof(fp)) {
fscanf(fp, "%1d", &dummy);
count[dummy]++;
}
fclose(fp);
long sum = 0;
for(i = 0; i < 10; i++)
sum += count[i];
for(i = 0; i < 10; i++)
printf("count[%d] = %7ld Percentage = %5.2f\n",
i, count[i], ((float)(100 * count[i])/sum));
}
如果生成大量随机数(1000000),则结果如下:
count[0] = 387432 Percentage = 8.31
count[1] = 728339 Percentage = 15.63
count[2] = 720880 Percentage = 15.47
count[3] = 475982 Percentage = 10.21
count[4] = 392678 Percentage = 8.43
count[5] = 392683 Percentage = 8.43
count[6] = 392456 Percentage = 8.42
count[7] = 391599 Percentage = 8.40
count[8] = 388795 Percentage = 8.34
count[9] = 389501 Percentage = 8.36
请注意,1、2和3的匹配次数过多。我已经尝试运行了几次,每次都得到非常相似的结果。
我试图了解什么可能导致1、2和3的出现频率比其他任何数字都高。
从马特·乔纳(Matt Joiner)和帕斯卡·库克(Pascal Cuoq)指出的事情中得出的提示,
我更改了要使用的代码
for(i = 0; i < 1000000; i++)
fprintf(fp, "%04d\n", rand() % 10000);
// pretty prints 0
// generates numbers in range 0000 to 9999
这就是我得到的(在多次运行中得到类似的结果):
count[0] = 422947 Percentage = 10.57
count[1] = 423222 Percentage = 10.58
count[2] = 414699 Percentage = 10.37
count[3] = 391604 Percentage = 9.79
count[4] = 392640 Percentage = 9.82
count[5] = 392928 Percentage = 9.82
count[6] = 392737 Percentage = 9.82
count[7] = 392634 Percentage = 9.82
count[8] = 388238 Percentage = 9.71
count[9] = 388352 Percentage = 9.71
偏爱0、1和2的原因可能是什么?
谢谢大家。使用
int rand2(){
int num = rand();
return (num > 30000? rand2():num);
}
fprintf(fp, "%04d\n", rand2() % 10000);
我懂了
count[0] = 399629 Percentage = 9.99
count[1] = 399897 Percentage = 10.00
count[2] = 400162 Percentage = 10.00
count[3] = 400412 Percentage = 10.01
count[4] = 399863 Percentage = 10.00
count[5] = 400756 Percentage = 10.02
count[6] = 399980 Percentage = 10.00
count[7] = 400055 Percentage = 10.00
count[8] = 399143 Percentage = 9.98
count[9] = 400104 Percentage = 10.00
最佳答案
rand()
生成从0
到RAND_MAX
的值。在大多数平台上,RAND_MAX
设置为INT_MAX
,可以是32767
或2147483647
。
对于上面给出的示例,看来RAND_MAX
是32767
。对于1
到2
的值的最高有效位,这将为3
,10000
和32767
设置异常高的频率。您可以观察到,在较小程度上,直到6
和7
的值也会稍受青睐。
关于c - 为什么使用C rand()函数如此频繁地显示数字1、2和3?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3381458/