C语言库函数中的rand()的用法??

王朝知道·作者佚名  2010-08-26
窄屏简体版  字體: |||超大  
 
分類: 電腦/網絡 >> 程序設計 >> 其他編程語言
 
問題描述:

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

小贴士:① 若网友所发内容与教科书相悖,请以教科书为准;② 若网友所发内容与科学常识、官方权威机构相悖,请以后者为准;③ 若网友所发内容不正确或者违背公序良俗,右下举报/纠错。
 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航