您的位置:首页 > 编程语言 > C语言/C++

C/C++生成随机数

2013-10-25 14:07 267 查看

原文转载自:http://www.oschina.net/code/snippet_54100_5029

1.[代码][C/C++]代码

01
#include
<stdio.h>
02
#include
<stdlib.h>
03
04
int
main(
int
argc,
char
*argv[])
05
{
06
int
i;
07
for
(i=0;
i<10;i++){
08
printf
(
"%d\n"
,
rand
());
09
}
10
return
0;
11
}

2.[代码][C/C++]代码

01
/*
02
上述方法产生随机数每次不同,但每次运行时产生的顺序是相同的。原因是每次的种子都相同,所以会产生相同的随机数列。一般使用时间作为种子保证每次的种子都不同。简单的实现代码:
03
*/
04
#include
<stdio.h>
05
#include
<stdlib.h>
06
#include
<time.h>
07
08
int
main(
int
argc,
char
*argv[])
09
{
10
int
i;
11
srand
((
int
)
time
(0));
12
for
(i=0;
i<10;i++){
13
printf
(
"%d\n"
,
rand
());
14
}
15
16
return
0;
17
}

3.[代码][C/C++]代码

01
/*
02
如果要产生其他范围内的整数,可以使用取余运算实现。以下代码为产生0~100之间的随机数:
03
*/
04
#include
<stdio.h>
05
#include
<stdlib.h>
06
#include
<time.h>
07
08
int
main(
int
argc,
char
*argv[])
09
{
10
int
i;
11
srand
((
int
)
time
(0));
12
for
(i=0;
i<10;i++){
13
printf
(
"%d\n"
,
rand
()%100);
14
}
15
16
return
0;
17
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: