include <stdlib.h>
#include <stdio.h>
#include<conio.h>
int main(void)
{
int i;
printf("Ten random numbers from 0 to 99\n\n");
for(i=0; i<10; i++)
printf("%d\n", rand()%100);
getch();
return 0;
}
为什么每次运行的结果都是一样的??关了重启结果还是一样!!
这结果哪像是随机啊?!!
求高手帮忙解释一下这个库函数的用法?如果能解释一下上面结果不随机问题最好.谢谢!
參考答案:一般情况下,随机函数都是以时间作为参考的。所以在使用时,可能需要初始化随机种子。
下面是MSDN对rand()函数说明的例子。
Example
Copy Code
// crt_rand.c
// This program seeds the random-number generator
// with the time, then displays 10 random integers.
//
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main( void )
{
int i;
// Seed the random-number generator with current time so that
// the numbers will be different every time we run.
//
srand( (unsigned)time( NULL ) );
// Display 10 numbers.
for( i = 0; i < 10;i++ )
printf( " %6d\n", rand() );
printf("\n");
// Usually, you will want to generate a number in a specific range,
// such as 0 to 100, like this:
{
int RANGE_MIN = 0;
int RANGE_MAX = 100;
for (i = 0; i < 10; i++ )
{
int rand100 = (((double) rand() /
(double) RAND_MAX) * RANGE_MAX + RANGE_MIN);
printf( " %6d\n", rand100);
}
}
}
Sample Output
24052
20577
2235
29883
26046
22303
19311
5143
3208
8804
49
90
91
16
21
16
91
68
30
31
参考资料:MSDN