【问题标题】:Creating a function thats generates a random number using srand and rand [duplicate]创建一个使用 srand 和 rand 生成随机数的函数 [重复]
【发布时间】:2021-10-23 07:53:07
【问题描述】:

尝试创建一个使用rand()srand() 生成随机数的函数。

此代码成功打印 3 个随机数:

//prints a random number from 1 to 10 3 times.
void main()
{
    int num;
    srand(time(NULL));
    num = rand() % 10;
    printf("%d\n", num);
    num = rand() % 10;
    printf("%d\n", num);
    num = rand() % 10;
    printf("%d\n", num);
}

//Output: 3 5 6

这个使用函数的代码没有:

//calls PrintRandomNumber 3 times.
void main()
    {
        int i=0, num;
        for(i=0; i<3; i++)
        {
        printRandomNumber(0, 10);
        }
    }

//Prints a random numberin the range of lowestValue to highestValue.
void printRandomNumber(int lowestValue, int highestValue)
{
    int randomNumber = 0;
    srand(time(NULL));
    randomNumber = (rand() % (highestValue - lowestValue + 1)) + lowestValue;
    printf("%d\n", randomNumber);
}
//Output: 3 3 3

问题是多次调用srand(time(NULL))

函数能否使用rand()srand() 打印/返回一个随机数,而不必在main 中调用srand(time(NULL))

【问题讨论】:

  • 只需拨打srand(time(NULL)); 一次 - 来自main,然后再执行任何其他操作。
  • ... 问题是因为您的三个函数调用在彼此之后运行得非常快,以至于当前时间不会改变,并且每次都得到相同的种子。
  • 回答您的最后(编辑)点 - 是的,您可以。只需使用其他东西作为 srand() 的参数,或者在调用之间等待。

标签: c function random-seed srand


【解决方案1】:

您可以按照以下示例进行操作:

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

int main () {
   int i, n;
   time_t t;
   
   n = 3;
   
   /* Intializes random number generator */
   srand((unsigned) time(&t));

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

【讨论】:

  • Meh - OP 想要 使用一个函数 - 你的代码只是对他们的第一个(工作)代码的微不足道的改进。
  • 无论如何,这是一个常见的重复(甚至可能有其他更好的目标)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-13
相关资源
最近更新 更多