C ++中从-9到9的随机数 [英] random number from -9 to 9 in C++

查看:21
本文介绍了C ++中从-9到9的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

just wondering, if I have the following code:

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

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

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

推荐答案

不,不会的.您正在寻找:

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

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

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

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.

这篇关于C ++中从-9到9的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆