下面是一段代码
#include <iostream>
#include <cstdio.h>
#include <time.h>
using namespace std;
int main()
{
time_t ts;
unsigned int sum = time(&ts);
srand(sum);
int data = rand()%100;
cout << data;
getchar();
return 0;
}
为什么每次运行都是打印同一个数
不应该不一样的吗
#include
#include
#include
using namespace std;
int main()
{
srand(static_cast(time(NULL))); // 初始化随机种子
int data = rand()%100;
cout << data;
getchar();
return 0;
}
我测试变。
试试这个:
#include <iostream>
//#include <cstdio.h>
#include <time.h>
using namespace std;
int main()
{
//time_t ts;
//unsigned int sum = time(&ts);
srand( (unsigned)time( NULL ) );
//srand(sum);
int data = rand()%100;
cout << data;
getchar();
return 0;
}
看了一下上面两位的代码,可能是机器设置问题,或者本身的c' api参数没有传递正确。
srand( (unsigned)time( NULL ) ); 必须得用时间种子,否则是伪随机的。。