C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C生成随机数而不重复大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > 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 array\n");

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,

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

大佬总结

以上是大佬教程为你收集整理的C生成随机数而不重复全部内容,希望文章能够帮你解决C生成随机数而不重复所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。