【问题标题】:Generate a Random Number between 1 and N-1 [duplicate]生成1到N-1之间的随机数[重复]
【发布时间】:2013-01-02 11:02:38
【问题描述】:

可能重复:
How to generate a random number from within a range - C

如何生成一个介于 1 和 N-1 之间的随机数,其中 N 是用户输入的数字?

到目前为止,我的代码是:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int number = 0; //number variable
    printf("This program will ask you for a number, an integer, and will print out a    random number from the range of your number 1, to N-1.");//output that explains the program's purpose and use to the user.
    //gets the input
    fgets(buffer, sizeof(buffer), stdin);
    sscanf(buffer, "%d", &number); //gets the input and stores it into variable number

    return (0);

}

【问题讨论】:

  • 提示:寻找一个返回随机数并使用模运算符的函数

标签: c random


【解决方案1】:

根据您希望数字的“随机”程度,您可以使用标准 libc 中的 rand() 函数。此函数将生成 0 和 RAND_MAX 之间的数字。然后,您可以使用模运算获得良好范围内的结果。

请注意,此生成器(LCG)既不适合加密应用也不科学应用。

如果您想要更合适的生成器,请查看 Mersenne Twister 等生成器(尽管仍然不是加密安全的)。

【讨论】:

  • NOT suitable for cryptographic applications nor scientific applications 从问题和上下文的外观来看,我认为我们不必担心这一点。 ;)
  • 当然,但这只是以防万一有人将此答案用于其他用途:-)
【解决方案2】:

试试这样的:-

unsigned int
randomr(unsigned int min, unsigned int max)
{
       double x= (double)rand()/RAND_MAX;

       return (max - min +1)*x+ min;
}

查看此链接:- http://c-faq.com/lib/randrange.html

【讨论】:

    【解决方案3】:

    这里是随机参考的链接。

    http://www.cplusplus.com/reference/cstdlib/rand/

    你可以使用

    num= rand() % n + 1;

    【讨论】:

    • 简单干净。我喜欢它
    【解决方案4】:

    您需要查看rand。一点数学,你就有了解决方案。

    【讨论】:

      猜你喜欢
      • 2013-12-21
      • 1970-01-01
      • 1970-01-01
      • 2014-04-11
      • 1970-01-01
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多