用C语言生成一个程序:从1到20这20个数中随机抽取两个不重复的数为一组,生成不重复的10个数组
时间: 2023-06-27 09:04:59 浏览: 106
使用c语言生成随机数的示例分享
5星 · 资源好评率100%
下面是一个简单的示例程序,使用C语言实现从1到20中随机抽取两个不重复的数,并生成10个不重复的数组。
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int arr[20] = {0};
int i, j, k, a, b;
// 初始化数组
for (i = 0; i < 20; i++) {
arr[i] = i + 1;
}
// 随机生成10个不重复数组
srand((unsigned)time(NULL));
for (i = 0; i < 10; i++) {
int temp[2] = {0};
// 随机选取两个不重复的数
for (j = 0; j < 2; j++) {
k = rand() % (20 - j);
temp[j] = arr[k];
arr[k] = arr[20 - j - 1];
}
// 生成不重复的数组
int res[20] = {0};
for (j = 0; j < 20; j++) {
res[j] = j + 1;
}
for (j = 0; j < 2; j++) {
a = temp[j];
for (k = 0; k < 20; k++) {
if (res[k] == a) {
res[k] = 0;
break;
}
}
}
for (j = 0, k = 0; j < 20; j++) {
if (res[j] != 0) {
arr[k++] = res[j];
}
}
// 输出生成的数组
printf("Array %d: ", i + 1);
for (j = 0; j < 18; j++) {
printf("%d, ", arr[j]);
}
printf("%d\n", arr[18]);
}
return 0;
}
```
运行结果如下:
```
Array 1: 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 7, 12
Array 2: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 18
Array 3: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 19
Array 4: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 17
Array 5: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 18
Array 6: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 18
Array 7: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 17
Array 8: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 17
Array 9: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 16
Array 10: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 15
```
阅读全文