我一直在寻找 C 代码来生成一组 [start, end]
范围内的随机偶数。我试过了,
int random = ((start + rand() % (end - start) / 2)) * 2;
这将不起作用,例如,如果范围是 [0, 4],则同时包括 0 和 4
int random = (0 + rand() % (4 - 0) / 2) * 2
=> (rand() % 2) * 2
=> 0, 2, ... (never includes 4) but expectation = 0, 2, 4 ...
另一方面,如果我使用,
int random = ((start + rand() % (end - start) / 2) + 1) * 2;
这行不通,例如,
int random = (0 + (rand() % (4 - 0) / 2) + 1) * 2
=> ((rand() % 4 / 2) + 1) * 2
=> 2, 4, ... (never includes 0) but expectation = 0, 2, 4 ...
有什么线索吗?如何摆脱这个问题?
最佳答案
你把它复杂化了。由于您使用的是 rand()
和模运算符,我假设您不会将其用于加密或安全目的,而是将其用作简单的偶数生成器。
我找到的用于生成 [0, 2n] 范围内的随机偶数的公式是使用
s = (rand() % (n + 1)) * 2
示例代码:
#include <stdio.h>
int main() {
int i, s;
for(i = 0; i < 100; i++) {
s = (rand() % 3) * 2;
printf("%d ", s);
}
}
它给了我以下输出:
2 2 0 2 4 2 2 0 0 2 4 2 4 2 4 2 0 0 2 2 4 4 0 0 4 4 4 2 2 2 4 0 0 0 4 0 2 2 2 2 0 0 0 4 4 2 4 4 4 0 4 2 2 4 4 0 4 4 2 2 0 0 4 0 4 4 2 0 2 4 0 0 0 0 4 0 4 4 0 4 2 0 0 4 4 0 0 4 4 2 0 0 4 0 2 2 2 0 0 4 0 2 4 2
最好的问候!
关于c - 生成 [m, n] 范围内的随机偶数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49232226/