C语言中如何实现在1到6中随机产生一个数字并存入数组中,一共存12次,如何保证每个数字只重复一次

[复制链接]
查看11 | 回复1 | 2011-3-5 06:50:24 | 显示全部楼层 |阅读模式
回复

使用道具 举报

千问 | 2011-3-5 06:50:24 | 显示全部楼层
<pre id=\"best-answer-content\" class=\"reply-text mb10\">#include stdio.h
#include stdlib.h
#include time.h
#define N 12
int main(int argc, char *argv[])
{
int i;
int x[N] = {1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6};

printf(\"之前数组: \");
for (i = 0; iN; i)

printf(\"=\", x);
printf(\"\\n\");

srand((unsigned)time(NULL));

for (i = N-1; i = 0; i--)
{

int rd = rand() % N;

int temp = x;

x = x [rd];

x[rd] = temp;
}

printf(\"之后数组: \");
for (i = 0; iN; i)

printf(\"=\", x);
printf(\"\\n\");

return 0;
}
——————————————————————————————————
其实该问题类似洗牌的程序,所有的数字其实都是已知的,只需要通过随机数去打乱这些数的次序就可以达到效果。先前的regret4hxp2的思路可以达到同样的效果,但是有个缺点是效率不高,而且需要引入同步的计数。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行