C++随机数

来源:百度知道 编辑:UC知道 时间:2024/06/21 16:36:37
定义个函数,它能生成N个随机数,N由函数参数指定,随机数值在0到1.0之间,包括0和1.0 !

#include <iostream>
#include <ctime>
#include <vector>
#include <algorithm>

using namespace std;

vector<double> Rnd( int N )
{
srand( (unsigned)time(NULL) ); //以当前系统时间来实现随机数种子
vector<double> v(N);
for(int i=0;i<N;i++)
{
v[i] = (double)(rand()%11)/10;
} //如果需要更精细,可以%101然后除以100,也可以%1001后再除以1000

return v;
}

int main()
{
vector<double> v = Rnd( 100 ); //这个100,可以手动输入哦。呵呵。
copy( v.begin(),v.end(),ostream_iterator<double>( cout," " ) );

return 0;
}

#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;

int UserFunction_1(int n)
{
static srand(time(NULL));
for(int i=0;i<n;i++)
cout<<((double)rand()-1)/32766; //int最大为32767
return 0;
}