【问题标题】:Generate different numbers in C using Random [duplicate]使用随机在C中生成不同的数字[重复]
【发布时间】:2014-01-06 07:56:41
【问题描述】:

所以基本上我用 C 语言编写了这个函数来生成从 1 到 50 的 5 个随机数:

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

int main() {
    int c, n;

    printf("Five random numbers from 1 to 50 \n");

    for (c = 1; c <= 5; c++) {
        n = rand()%50 + 1;
        printf("%d\n", n);
    }

    return 0;
}

我想知道如何确定此代码生成的数字彼此不同。

有什么帮助吗?

【问题讨论】:

  • 你不能这是随机的性质,如果你存储以前的你可以比较那些,否则你不能。事实上,rand 只有 16 位非常差的伪随机性,这几乎是一种保证。这种特殊设置也不会产生均匀分布。如果你想使用更好的随机我建议random_r
  • 如果你想要 50 中的五个 distinct 数字,你可以对 1..50 的序列进行随机播放(使用 rand() 和一个像样的随机播放算法,例如七遍-swap),然后从序列中取出前五个数字。还有其他方法,但这很类似于从您的描述中洗牌。
  • 你能举个小例子吗@Mgetz?
  • @WhozCraig 你能举个例子吗?
  • 当然。 See it live。但是,您应该在下面查看 BLUEPIXY 的答案,因为它的效率要高得多。

标签: c random


【解决方案1】:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void swap(int *a, int *b){
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int i, c, n, size = 50;
    int data[size];

    srand(time(NULL));
    for(i=0;i<size;++i)
        data[i] = i+1;

    printf("Five random numbers from 1 to 50 \n");

    for (c = 1; c <= 5; c++) {
        n = rand()%size;
        printf("%d\n", data[n]);
        swap(&data[--size], &data[n]);
    }

    return 0;
}

【讨论】:

  • +1 这是一个优秀的答案,OP 会明智地逐步了解它是如何工作的。
  • 这是一个很好的程序,但不要只是转储代码供人们复制和粘贴。添加一些解释,以便他们学习。
  • 参见:How not to shuffle — The Knuth Fisher-Yates AlgorithmShuffle — Shuffle a deck of cards — Knuth shufleWikipedia — Fisher-Yates Shuffle。或者对网络进行自己的评估。我使用谷歌搜索“knuth shuffle proof”。
  • @Kninnug 我同意,并且可能应该更具体。这是一个很好的实现,可以肯定的是,“为什么”需要一些内容。
  • 我认为没有什么地方是难到需要解释的。但我一直在写。 (1)我将准备所需的卡号。 (2)我会在卡片要求的范围内填写数字。 (3)拔出选卡。 (4)我根据需要重复(3)。
【解决方案2】:

将每个数字存储在一个数组中,并根据现有条目检查每个新随机数。

【讨论】:

    【解决方案3】:

    您应该像这样检查所有数字:

    #include <time.h>
    
    int randomNumbers[5];
    int c, d, n;
    bool itIsNew;
    
    //current time as random seed
    srand(time(0));
    
    for (c = 1; c <= 5;)
    {
        n = rand() % 50 + 1;
        itIsNew = true;
    
        for(d = 1; d <= c; d++)
        {
            if(n == randomNumbers[d - 1])
            {
                itIsNew = false;
                break;
            }       
        }
        if(itIsNew)
        {
            randomNumbers[c - 1] = n;
            c++;
        }
    }
    

    【讨论】:

    • 请学习从 0 到小于限制运行循环:for (d = 0; d &lt; c; d++) 等;这样,您就不必在下标中使用 d - 1
    猜你喜欢
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 2011-06-12
    • 2016-08-20
    • 2013-11-12
    • 2015-07-12
    • 1970-01-01
    相关资源
    最近更新 更多