简体   繁体   English

随机 function 总是返回 1

[英]Random function always returns 1

My random function always returns a "1" rather than... anything我的随机 function 总是返回“1”而不是......任何东西
It is supposed to return a "0" or "1"它应该返回“0”或“1”

int rnd() {
    unsigned int num0 = rand();
    if(num0 < 32767.5) {return 0;}
    if(num0 > 32767.5) {return 1;}
}

int chk;
bool _True = true;

int main(void) {
    while(_True) {
        chk = rnd();
        printf("%i\n", chk);
        //if(chk == 1) {printf("%i\n", chk); _True = false;}
        //if(chk == 0) {printf("%i\n", chk); _True = false;}
    }
}

First, rand() gives a pseudo-random number based on a seed.首先,rand() 给出基于种子的伪随机数。 If you don't call srand() before rand(), you will get the same sequence of random numbers every time you run the program.如果在 rand() 之前不调用 srand(),那么每次运行程序都会得到相同的随机数序列。

Second, the rand() function returns a pseudo-random number in the range of 0 to RAND_MAX.其次,rand() function 返回一个 0 到 RAND_MAX 范围内的伪随机数。

RAND_MAX is a constant whose default value may vary between implementations but it is guaranteed to be at least 32767. RAND_MAX 是一个常量,其默认值可能因实现而异,但保证至少为 32767。

You seem to be assuming RAND_MAX is twice 32767.5?您似乎假设 RAND_MAX 是 32767.5 的两倍?

I would suggest calling srand() first and then testing versus RAND_MAX / 2, or setting your value to rand() % 2 instead.我建议先调用 srand() 然后测试 RAND_MAX / 2,或者将你的值设置为 rand() % 2。

(You could have determined such by printing what rand() was returning, and/or by looking up the documentation of rand().) (您可以通过打印 rand() 返回的内容和/或查看 rand() 的文档来确定这一点。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM