1.使用随机数生成指定数量,指定最小值的不会重复的随机数
#include <iostream>
using namespace std;
void rrand(int arr[], const size_t len, const int min)
{
srand(time(0));//根据当前时间初始化随机种子
for (int ii = 0; ii < len; ii++)
{
while (1)
{
int temp = rand() % len + min;//获得一个最小值为min,最大值为len+min-1的随机数
int jj=0;
for (; jj < ii; jj++)
if (temp == arr[jj]) break;
if (jj == ii)
{
arr[ii] = temp;
break;
}
}
}
}
int main()
{
int arr[100]={0};
int x, y;
while (1)
{
cout << "请输入生成随机数的个数:";
cin >> x;
if (x < 1 || x>100)
{
cout << "范围为0到100";
}
else
break;
}
while (1)
{
cout << "请输入生成随机数的最小值:";
cin >> y;
if (y < 0|| y>x)
{
cout << "请重新输入:"<<endl;
}
else
break;
}
rrand(arr, x, y);
for (int i = 0; i < x; i++)
{
cout << arr[i] << endl;
}
}
2.随机发52张卡牌给四个人
将main函数替换为下面内容
int arr[52];
rrand(arr, 52, 1);
cout << "洗好的牌为:" << endl;
for (int i = 0; i < 52; i++)
{
cout << arr[i] << "\t";
}
cout << endl<<endl;
int arr2[4][13] = {0};
int m=0;
for (int ii = 0; ii < 4; ii++)
{
for (int jj = 0; jj < 13; jj++)
{
arr2[ii][jj] = arr[m];
m+=4;
}
m = ii + 1;
}
for (int ii = 0; ii < 4; ii++)
{
cout << "第" << ii+1 << "个人的卡牌是:";
for (int jj = 0; jj < 13; jj++)
{
cout << arr2[ii][jj] << "\t";
}
cout << endl<<endl;
}