你可以做
cout << rawRand % 100 << endl; // Outputs between 0 and 99
cout << rawRand % 101 << endl; // outputs between 0 and 100
对于投反对票的人;请注意,在最初发布此内容一分钟后,我留下了评论:
来自http://www.cplusplus.com/reference/clibrary/cstdlib/rand “请注意,尽管此模运算不会在跨度中生成真正均匀分布的随机数(因为在大多数情况下,较小的数字更有可能),但它通常是短跨度的一个很好的近似值。”
使用 64 位整数并使用 100 个数字作为输出,数字 0-16 用 1.00000000000000000455 % 的数字表示(与 1% 同分布的相对精度约为 10 -18),而数字 17-99 则表示0.99999999999999999913 % 的数字。是的,不是完全分布,但对于小跨度来说是一个非常好的近似值。
另请注意,OP 在哪里要求相同分布的数字?据我们所知,这些被用于小偏差无关紧要的目的(例如,除了密码学之外的任何东西——如果他们使用数字进行密码学,这个问题对于他们来说太天真了,无法编写自己的密码学)。
编辑- 对于真正关心随机数均匀分布的人,以下代码有效。请注意,这不一定像 64 位随机整数那样是最佳的,它需要rand()
每 10^18 次调用两次调用一次。
unsigned N = 100; // want numbers 0-99
unsigned long randTruncation = (RAND_MAX / N) * N;
// include every number the N times by ensuring rawRand is between 0 and randTruncation - 1 or regenerate.
unsigned long rawRand = rand();
while (rawRand >= randTruncation) {
rawRand = rand();
// with 64-bit int and range of 0-99 will need to generate two random numbers
// about 1 in every (2^63)/16 ~ 10^18 times (1 million million times)
// with 32-bit int and range of 0-99 will need to generate two random numbers
// once every 46 million times.
}
cout << rawRand % N << stdl::endl;