详细解释:链接
应用:
随机抽取数组中的数
//有放回-------------------
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include <stdlib.h>
#include <time.h>
#include<math.h>
using namespace std;
const int N=17;
int a[N]={20,31,50,52,56,60,63,72,110,112};
int main()
{
int i,n = 10,m = 4;
srand((unsigned)time(NULL));
printf("有放回抽取结果为:");
int x;
for(i=0;i<m;i++)
{
x=rand()%n;
printf("%d ",a[x]);
}
return 0;
}
随机抽取数组中不同的数
//无放回------------------------------
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include <stdlib.h>
#include <time.h>
#include<math.h>
using namespace std;
const int N=17;
int a[N]={20,31,50,52,56,60,63,72,110,112};
int main()
{
int b[10] = {0}; //b[N]用来记录数组中的数是否已经输出
int n = 10,m = 4;
printf("不放回抽取结果为:");
srand((unsigned)time(NULL));//初始化随机种子
int x;
for(int i=0;i<m;i++)
{
x=rand()%n;//rand()为产生的一个随机数
if(b[x] == 0) //保证产生的数不重复
{
b[x] = 1;
printf("%d ",a[x]);
}
else
i--;
}
return 0;
}