C语言生成随机数:详解rand()函数及应用
#include<stdio.h> #include <stdlib.h> #include<time.h> #define M 100 int main(){ int a[M]; int i,n; n=M;
srand( time(NULL) );
for( i = 0; i <n; i++ ) {
a[i]=rand()%11;
printf( "%d: %d\n", i,a[i] );
}
} 数组大小是100,但是运行结果没有一百个数内容:这是因为程序中使用了rand()函数生成随机数,而rand()函数生成的是一个在0到RAND_MAX之间的伪随机数。RAND_MAX的值在不同的系统中可能有所不同,但通常是32767。所以在这个程序中,生成的随机数最大值是10,而不是100。
如果你想生成100个0到100之间的随机数,可以将rand()%11改为rand()%101,这样就可以生成100个随机数了。
原文地址: https://www.cveoy.top/t/topic/p1Ux 著作权归作者所有。请勿转载和采集!