求助!如果随机匹配n个数,要实现两两配对,若共有奇数个数则随机选一个数来配对两个数。的代码_(:з」∠)_
你题目的解答代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int n=9, i, j, x,y;
int a[n];
int b[n];
srand((unsigned)time(NULL));
for( i=0; i<n; i++ )
{
a[i] = i+1; //这里直接赋值1到9了,也可以改成 scanf("%d", &a[i]); 读取用户输入
b[i] = 0;
}
for( i=0; i<n/2; i++ )
{
do{
x = rand() % n;
} while (b[x]);
b[x] = 1;
do{
y = rand() % n;
} while (b[y]);
b[y] = 1;
printf("%d %d\n", a[x],a[y]);
}
if (n%2==1)
{
for (x = 0; b[x]; x++) { }
b[x] = 1;
do{
y = rand() % n;
} while (y==x);
b[y] = 1;
printf("%d %d\n", a[x],a[y]);
}
return 0;
}
如有帮助,望采纳!谢谢!