C语言 随机数:0 或 1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21579696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:44:26  来源:igfitidea点击:

Random Number: either 0 or 1

crandom

提问by g_rmz

I've this code:

我有这个代码:

srand(time(NULL));
int n = rand() % 1 + 0;
printf("%d\n", n);

But, if i put it (notsrand(time(NULL))) in a loop for e.g., it generates only a sequence of 0. There is another implementation for the random numbers between 0 and 1 or i've forgot something?

但是,如果我把它(不是srand(time(NULL)))放在一个循环中,例如,它只生成一个 0 的序列。0 和 1 之间的随机数还有另一种实现,或者我忘了什么?

回答by unwind

If you meant 0 or1, your %makes some sense, but you meant % 2(or & 1). Of course, the + 0is still rather pointless, no idea what you're aiming for there. For an integer result of 0 or 1, just do:

如果你的意思是 01,%你的意思是有道理的,但你的意思是% 2(或& 1)。当然,这+ 0仍然相当没有意义,不知道你的目标是什么。对于 0 或 1 的整数结果,只需执行以下操作:

const randomBit = rand() % 2;

The compiler will probably "strength-reduce"that to:

编译器可能会将其“强度降低”为:

const randomBit = rand() & 1;

Also, make sure you only call srand()oncein your program or it won't have the effect you expect.

另外,请确保您在程序中只调用srand()一次,否则它不会产生您期望的效果。

回答by Hayri U?ur Koltuk

If you want either 0 or 1, just do

如果你想要 0 或 1,就做

int n = rand() % 2

if what rand returns is even you'll get a 0, and if it's odd you'll get a 1 here.

如果 rand 返回的是偶数,您将得到 0,如果是奇数,您将在这里得到 1。

回答by haccks

int n = rand() % 1 + 0;  

will produce 0always as rand() % 1gives 0(rand()%agenerates number between 0to a-1).

0始终按rand() % 1给定的方式产生0rand()%a0to之间生成数字a-1)。

回答by Phi Nguyen

std::srand(time(0)); //Randomise seed initialisation
for (int rows = 0; rows < n; rows++) {
    int randNum = rand() % 2;
}