Generate a random number from 0 to 10000000

馋奶兔 提交于 2020-07-11 05:42:12

问题


How can I generate random numbers from 0 to 1000000?

I already tried the code below, but it still gives me numbers from 0 to 32767 (RAND_MAX):

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

int main(){
    int i,x;
    srand(time(NULL));
    for(i=0; i<10000; i++){
        int x = rand() % 10000000 + 1;
        printf("%d\n",x);
    }
    return 0;
}

回答1:


[Edit] The initial answer was for 0 to 1,000,000. I now see it should be 0 to 10,000,000.

As rand() will give an answer of at least 15 bits, call rand() multiple times, shift by 15 and XOR the results. Finally mod by 10,000,001.

unsigned long x;
x = rand();
x <<= 15;
x ^= rand();
x %= 10000001;

The distribution is very flat, but does introduce a very small bias. After 32768*32768 iterations, each value of x 0 to 10,000,000 to occur about 107.37 times. Instead they range from 107 to 108 times.

Combining multiple rand() call results with +, * or | will cause a significant bias in the distribution of the results.

[Edit]

RAND_MAX is 32767 (0x7FFF) for OP's platform. The C spec says "value of the RAND_MAX macro shall be at least 32767". Because RAND_MAX may be longer than 15 bits, it is important to use the ^ operator above rather than | for this code when used on other platforms.




回答2:


Calculate with % 1000001 if you want numbers between 0 and 1000000. Also RAND_MAX is conly guaranteed to be at least 32767

int main(){
  int i, x;
  srand(time(NULL));
  for(i=0; i<10000; i++){
    x = (rand() * rand()) % 1000001;
    printf("%d\n",x);
  }
  return 0;
}



回答3:


Use this function, it will give you random number between two number (min and max) :

unsigned long int my_rand (unsigned long int Min, unsigned long int Max)
{
  static int first = 0;
  if (first == 0)
  {
    srand (time (NULL)); //initialize generator of random number
    first = 1;
  }
  return ((unsigned long int)(rand() * (Max+1 - Min) / RAND_MAX + Min));
}


来源:https://stackoverflow.com/questions/19870276/generate-a-random-number-from-0-to-10000000

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!