简体   繁体   中英

Random function always returns 1

My random function always returns a "1" rather than... anything
It is supposed to return a "0" or "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. If you don't call srand() before rand(), you will get the same sequence of random numbers every time you run the program.

Second, the rand() function returns a pseudo-random number in the range of 0 to RAND_MAX.

RAND_MAX is a constant whose default value may vary between implementations but it is guaranteed to be at least 32767.

You seem to be assuming RAND_MAX is twice 32767.5?

I would suggest calling srand() first and then testing versus RAND_MAX / 2, or setting your value to rand() % 2 instead.

(You could have determined such by printing what rand() was returning, and/or by looking up the documentation of rand().)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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