在vc++中程序中用了srandom()和random(),头文件为stdlib.h,但编译出现错误error C3861: “srandom”: 找不到标识符。
原因是现在vc++编译器的库函数中没有randomize()和random(),分别用srand()和rand()代替了。
#include <time.h> //定义关于时间的函数
一般在用到time(NULL)(当前时间)函数时需要包含此头文件
#include <stdlib.h> //定义杂项函数及内存分配函数
一般在用到rand()和srand()函数时需要包含此头文件
函数名: random 功 能: 随机数发生器,也就是产生一个随机数
用 法: int random(int num);
产生的随机数范围为0~num-1。
函数名: randomize
功 能: 初始化随机数发生器,相当于拨随机种子
用 法: void randomize(void);
#include <iostream>
#include <stdlib.h> // Need random(), srandom()
#include <time.h> // Need time()
#include <algorithm> // Need sort(), copy()
#include <vector> // Need vector
using namespace std;
void Display(vector<int>& v, const char* s);
int main()
{
// Seed the random number generator
srand(time(NULL));
// Construct vector and fill with random integer values
vector<int> collection(10);
for (int i = 0; i < 10; i++)
collection[i] = rand() % 10000;
// Display, sort, and redisplay
Display(collection, "Before sorting");
sort(collection.begin(), collection.end());
Display(collection, "After sorting");
return 0;
}
// Display label s and contents of integer vector v
void Display(vector<int>& v, const char* s)
{
cout << endl << s << endl;
copy(v.begin(), v.end(),ostream_iterator<int>(cout, "\t"));
cout << endl;
}
本文介绍在VC++环境中如何正确使用随机数生成函数srand()和rand()替代已弃用的srandom()和random(),并演示了一个利用这些函数填充数组并进行排序的例子。
7万+

被折叠的 条评论
为什么被折叠?



