不匹配的随机数 [英] Random numbers that do not match each other

查看:66
本文介绍了不匹配的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 C 生成不同的数字.我们可以使用 stdlib 库和 srand 函数生成一个随机数.

I want to produce different numbers with C. We can generate a random number using the stdlib library and the srand function.

例如;我想产生一个 0 到 5 之间的随机数.

For example; I want to produce a random number between 0 and 5.

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main(void)
{
int i;
int n = 4;
int array[3];

srand(time(NULL));

for(i = 0; i < n; i++)
{
   array[i] = rand() % 5; 
   printf("%d\n", array[i]);
}
return 0;

<小时>

但相同的数字可能在这里重合.就像这样:


But the same numbers may coincide here.Like this:

2
4
4
1

我怎样才能防止这种情况发生?

How can I prevent this?

推荐答案

也许你可以这样使用:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main(void)
{
    int i;
    int n = 4;
    int array[4];

    // Fill an array with possible values
    int values[5] = {0, 1, 2, 3, 4};

    srand(time(NULL));

    for(i = 0; i < n; i++)
    {
       int t1 = rand() % (5-i);   // Generate next index while making the
                                  // possible value one lesser for each
                                  // loop

       array[i] = values[t1];     // Assign value
       printf("%d\n", array[i]);

       values[t1] = values[4-i];  // Get rid of the used value by
                                  // replacing it with an unused value
    }
    return 0;
}

这篇关于不匹配的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆