生成一个从 0 到 10000000 的随机数 [英] Generate a random number from 0 to 10000000

查看:204
本文介绍了生成一个从 0 到 10000000 的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何生成从 0 到 1000000 的随机数?

How can I generate random numbers from 0 to 1000000?

我已经尝试过下面的代码,但它仍然给我从 0 到 32767 (RAND_MAX) 的数字:

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;
}

推荐答案

最初的答案是 0 到 1,000,000.我现在看到它应该是 0 到 10,000,000.

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

由于 rand() 将给出至少 15 位的答案,因此多次调用 rand(),移位 15 并对结果进行异或.最后修改了 10,000,001.

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;

分布非常平坦,但确实引入了非常很小的偏差.在 32768*32768 次迭代后,x 0 到 10,000,000 的每个值发生大约 107.37 次.相反,它们的范围从 107 到 108 次.

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.

将多个 rand() 调用结果与 +*| 组合将导致显着偏差结果的分布.

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

RAND_MAX 是 32767 (0x7FFF) 对于 OP 的平台.C 规范说RAND_MAX 宏的值应至少为 32767".由于 RAND_MAX 可能长于 15 位,因此在其他平台上使用此代码时,重要的是使用上面的 ^ 运算符而不是 |.

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.

这篇关于生成一个从 0 到 10000000 的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆