生成某一区间的随机数
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;
}
/*生成[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;
}
相关文章推荐
- JavaScript生成某个区间的随机数
- rand函数和srand函数的用法和区别+产生指定区间的随机数如何生成
- C语言区间随机数生成 with srand() & rand() & time() (转)
- 生成区间[a,b)中的随机数
- C语言区间随机数生成 with srand() & rand() & time()
- 生成任意区间的随机数
- python生成某区间内不重复的随机数
- 生成区间内互不重复的随机数序列
- C#在一段数字区间内随机生成若干个互不相同的随机数
- 在指定区间内,生成K个随机数
- sql server生成1000-9999之间的随机数或一个日期区间随机日期
- C#在一段数字区间内随机生成若干个互不相同的随机数
- C语言区间随机数生成 with srand() & rand() & time()
- java 生成特定区间的随机数
- 生成任意区间的随机数
- c语言中生成某一范围的随机数
- Random使用和生成某区间的随机数
- C语言区间随机数生成 with srand() & rand() & time() (转)
- CSDN专帖系列之一: 根据某一特殊规律的概率生成随机数
- C 产生某一区间随机数