您的位置:首页 > 其它

生成某一区间的随机数

2009-08-12 05:57 645 查看
/*---------------------------------------------------------*/
/*生成[a,b]之间的随机整数和浮点数                          */
/*By Edison Wang            Date:   2009-7-25              */

#include <cstdlib>
#include <iostream>
using namespace std;

int rand_int(int a, int b);    //获得a,b之间的一个随机整数
double rand_float(double a, double b);  //获得a,b之间的一个随机小数

int main(){
unsigned int seed;
int n,a,b,type(0);
double x,y;

cout <<"Enter a positive integer seed value: \n";  // 输入随机种子
cin >> seed;
srand(seed);

cout <<"Enter the number of random digits: \n";  // 输入随机数的个数
cin >> n;

cout <<"Enter type of random numbers (0.integer, 1.double): \n";  // 输入随机数的类型
cin >> type;
if (type==0) {
cout <<"Enter integer limits a and b (a<b): \n";  //输入整型随机数的范围
cin >> a >> b;
cout <<"Random Numbers: \n";
for(int k=1;k<=n;k++){
cout << rand_int(a,b) << ' ';
}
}
else{
cout <<"Enter double limits x and y (x<y): \n"; //输入浮点型随机数的范围
cin >> x >> y;
for(int m=1;m<=n;m++){
cout << rand_float(x,y) << ' ';
}
}
cout << endl;

cout << endl;

return 0;
}

//获得a,b之间的一个随机整数
int rand_int(int a, int b){
return rand()%(b-a+1)+a;
}

//获得a,b之间的一个随机小数
double rand_float(double a, double b){
return ((double)rand()/RAND_MAX)*(b-a)+a;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: