c语言rand函数在那个库,C语言库函数中的rand()的用法??

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

來源:互聯網  2010-08-26 11:46:47  評論

分類: 電腦/網絡 >> 程序設計 >> 其他編程語言

問題描述:

include

#include

#include

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

#include

#include

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

[b]分类:[/b] 电脑/网络 >> 程序设计 >> 其他编程语言[br][b]问题描述:[/b][br]include

#include

#include

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;

}

为什么每次运行的结果都是一样的??关了重启结果还是一样!!

这结果哪像是随机啊?!!

求高手帮忙解释一下这个库函数的用法?如果能解释一下上面结果不随机问题最好.谢谢![br][b]参考答案:[/b][br]一般情况下,随机函数都是以时间作为参考的。所以在使用时,可能需要初始化随机种子。

下面是MSDN对rand()函数说明的例子。

Example

Copy Code

// crt_rand.c

// This program seeds the random-number generator

// with the time, then displays 10 random integers.

//

#include

#include

#include

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值