生成指定区间内的随机数

 1 #include<iostream>
 2 #include<stdlib.h>
 3 #include<time.h>
 4 using namespace std;
 5 int main(){
 6     srand((unsigned)time(NULL));
 7     int l, r, i, n;
 8     cout<<"输入要生成随机数的区间, 以及个数:";
 9     cin>>l>>r>>n;
10     for(i=0; i<n; i++) cout<<rand()%(r-l+1)+l<<endl;
11     return 0;
12  }

 rand()能输出的最大随机数是32767, 如果要生成最大的随机数应该采用下面的方法

 1 #include<iostream>
 2 #include<stdlib.h>
 3 #include<time.h>
 4 using namespace std;
 5 int main(){
 6     srand((unsigned)time(NULL));
 7     int l, r, i, n;
 8     cout<<"能产生的最大随机数:"<<RAND_MAX<<endl;
 9     cout<<"输入要生成随机数的区间, 以及个数:";
10     cin>>l>>r>>n;
11     for(i=0; i<n; i++) cout<<(int)(1.0*rand()/RAND_MAX*l + r-l)<<endl;
12     return 0;
13  }

猜你喜欢

转载自www.cnblogs.com/mr-stn/p/9224914.html