| #include <stdlib.h> int rand(void); void srand(unsigned int seed); |
默认seed为1,编程中可以自己随意设置,伪随机就是每次得到的数据有规律可循,默认情况下数字在1~0x7fff,也就是(1~32767)。 |
| //使用默认种子1,编程 #include<iostream>
using namespace std;
int main()
{
for(int idx=0;idx!=10;++idx)
{ //默认seed==1
cout<<rand()<<" ";
}
cout<<endl;
system("pause");
}
//41 18467 6334 26500 19169 15724 11478 29358 26962 24464
//多次运行同一个结果
|
//使用指定种子 #include<iostream>
using namespace std;
int main()
{
srand(100); //数据范围在100~32767
for(int idx=0;idx!=10;++idx)
{
cout<<rand()<<" ";
}
cout<<endl;
system("pause");
}
//365 1216 5415 16704 24504 11254 24698 1702 23209 5629
|
|
#include <time.h>
time_t time(time_t *tloc);
//接口说明:
time() returns the time as the number of seconds since the Epoch,1970-01-01 00:00:00 +0000 (UTC).
If tloc is non-NULL, the return value is also stored in the memory pointed to by tloc.
|
//要想每次随机结果不一样,就要每次运行更改种子,time函数返回当前时间距离197-01-01的描述,每次运行都不一样,正好可以当做种子 #include<iostream>
#include<time.h>
using namespace std;
int main()
{
srand(time(NULL));
for(int idx=0;idx!=10;++idx)
{
cout<<rand()<<" ";
}
cout<<endl;
system("pause");
}
|
浙公网安备 33010602011771号