加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C生成随机数而不重复

发布时间:2020-12-16 10:09:29 所属栏目:百科 来源:网络整理
导读:参见英文答案 Generating list of random numbers without duplication using C?????????????????????????????????????5个 我想生成1到13之间的随机数而不重复 我使用这种方法,但它不能确保没有声誉. for ( i = 0; i 13; i++){ array[i] = 1 + (rand() % 13)
参见英文答案 > Generating list of random numbers without duplication using C?????????????????????????????????????5个
我想生成1到13之间的随机数而不重复
我使用这种方法,但它不能确保没有声誉.

for ( i = 0; i < 13; i++)
{
      array[i] = 1 + (rand() % 13);
}

请帮我.
C语言

解决方法

正如评论所说,填充数字1到13的数组然后洗牌阵列.

int array[13];

for (int i = 0; i < 13; i++) {     // fill array
    array[i] = i;
    printf("%d,",array[i]);
}
printf("n done with population n");
printf("here is the final arrayn");

for (int i = 0; i < 13; i++) {    // shuffle array
    int temp = array[i];
    int randomIndex = rand() % 13;

    array[i]           = array[randomIndex];
    array[randomIndex] = temp;
}


for (int i = 0; i < 13; i++) {    // print array
    printf("%d,array[i]);
}

这是示例输出.

0,1,2,3,4,5,6,7,8,9,10,11,12,done with population 
here is the final array
11,

注意:我使用了最基本的排序.如果你愿意,可以使用更好的一个.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读