gpt4 book ai didi

c++ - C++中从-9到9的随机数

转载 作者:IT老高 更新时间:2023-10-28 22:32:02 24 4
gpt4 key购买 nike

只是想知道,如果我有以下代码:

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

这会创建一个从 -9 到 9 的随机数吗?

最佳答案

不,不会。您正在寻找:

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

-9 和 +9 之间有 19 个不同的整数(包括两者),但 rand() % 18 只给出了 18 种可能性。这就是为什么你需要使用 rand() % 19

关于c++ - C++中从-9到9的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7887941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com