random number from -9 to 9 in C++

后端 未结 5 2101
伪装坚强ぢ
伪装坚强ぢ 2020-12-31 03:50

just wondering, if I have the following code:

int randomNum = rand() % 18 + (-9);

will this create a random number from -9 to 9?

5条回答
  •  渐次进展
    2020-12-31 04:26

    No, it won't. You're looking for:

    int randomNum = rand() % 19 + (-9);
    

    There are 19 distinct integers between -9 and +9 (including both), but rand() % 18 only gives 18 possibilities. This is why you need to use rand() % 19.

提交回复
热议问题