伪随机数函数 rand(); srand() 的简单实现 - yanbin's Blog

伪随机数函数 rand(); srand() 的简单实现

yanbin posted @ 2015年3月15日 23:49 in Programming with tags programming , 1425 阅读

	
 
static unsigned long next = 1;
static unsigned long myrand(void)
{
    next = next * 1103515245 + 12345;
    return ((unsigned)(next/65536) % 32768);
}

static void mysrand(unsigned long speed)
{
    next = speed;
}

/* example */
int main(int argc, char **argv)
{
    int j, r, nloops;
    unsigned long speed;

     if (argc < 2) {
         fprintf(stderr, "usage: %s <speed> <nloops>\n", argv[0]);
         exit(EXIT_FAILURE);
     }

     speed = strtol(argv[1], NULL, 10);
     nloops = atoi(argv[2]);
     
      mysrand(speed);
      for (j = 0; j < nloops; ++j) {
         r = myrand();
         fprintf(stderr, "%lu\n", r);
     }

     exit(EXIT_SUCCESS);
} 
 
 
 
 

 

Avatar_small
reese 说:
2022年11月30日 19:59

One simple implementation of the pseudo-random number function rand(); srand() is to use the linear congruential generator. This method uses a seed value to generate a sequence of numbers buy homes Cullowhee that appear to be random. The seed value can be any number, but is usually set to the current time so that the sequence is different each time the program is run.

Avatar_small
charlly 说:
2022年12月22日 13:58

To generate a pseudo-random number in C++, we can use the rand() function. This function takes a seed as an argument, which can be generated using the srand() function. peter veres art and photography The rand() function will return a number between 0 and RAND_MAX, which is a constant defined in the C++ standard.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter
Host by is-Programmer.com | Power by Chito 1.3.3 beta | © 2007 LinuxGem | Design by Matthew "Agent Spork" McGee