#include <iostream> #include <cstdlib> //srand()、rand() #include <ctime> //time()
using namespace std;
int main() { int i; srand((unsigned)time(NULL));//以time()为种子,time()返回值类型为
time_t,一般需要进行类型显示转换。
for(i=0; i<10; i++) { cout<<rand()%1000<<" ";//产生0~999之间的随机数 }
return 0; }
|
(1)rand(); 产生的随机数范围不确定
(2)rand()%100; 产生0~99范围的随机数
(3)rand()%100 + 1; 产生1~100范围的随机数
(4)rand()%50 + 2001; 产生2001~2050范围的随机数
上面代码用到的函数的原型:
time_t time(time_t* tp); Returns current calendar time or -1 if not available. If tp is non-NULL, return value is also assigned to *tp.
int rand(void); Returns pseudo-random number in range 0 to RAND_MAX.
void srand(unsigned int seed); Uses seed as seed for new sequence of pseudo-random numbers. Initial seed is 1.
|
阅读(775) | 评论(0) | 转发(0) |