以下记录两种方法,原理都是首先必须有一组不相同的数,
第一种
#include<iostream>
#include<cstdlib>
#include<time.h>
using namespace std;
void main()
{
srand((unsigned)time(NULL));
int n = 10;
int m = 3;
for (int i = 0; i < n; i++)
{
if ((rand() % (n-i) < m))
{
cout << i << " ";
m--;
}
if (m == 0)
break;
}
system("pause");
}
第二种
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
void swap(int &a, int &b)
{
int c = a;
a = b;
b = c;
}
void main()
{
int a[100];
for (int i = 0; i < 100; i++)
{
a[i] = i;
}
srand((unsigned)time(NULL));
for (int i = 0; i < 100; i++)
{
swap(a[i], a[rand() % 99 + 0]);
}
for (int i = 0; i < 100; i++)
{
cout << a[i] << " ";
}
system("pause");
}