简体   繁体   中英

Rand function with two different result

my question is about rand function in c++ please check this, why this generate different results:

int a = 2 * rand()%5; // result = 0
int a = 2 * ( rand()%5 ); // result = 6

number 1

number 2

Notwithstanding the fact that you'd rather hope that the probability of rand() returning a different number on the second iteration is 1 - 1 / (1 + RAND_MAX) , the first expression is grouped as

(2 * rand()) % 5

which is different to the second grouping. You can see for example that the value of the second expression is always even.

* and % have the same precedence , so associativity comes into play, which for both operators is left to right.

Because that's literally the purpose of rand() . As cppreference states :

Returns a pseudo-random integral number in the range between 0 and RAND_MAX .

You want it to produce different results otherwise it'd be a useless PRNG.

Plus the fact that the first expression first multiplies and then modulo's. While the second one does it in reverse.

To get the same values you have to fix your operator precedence and then call srand with the same seed twice right before calling rand() .


Note that you should use the <random> header nowadays instead 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