random number from -9 to 9 in C++

白昼怎懂夜的黑 提交于 2019-11-30 17:35:08

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.

Your code returns number between (0-9 and 17-9) = (-9 and 8).

For your information

 rand() % N;

returns number between 0 and N-1 :)

The right code is

rand() % 19 + (-9);

Do not forget the new C++11 pseudo-random functionality, could be an option if your compiler already supports it.

Pseudo-code:

std::mt19937 gen(someSeed);
std::uniform_int_distribution<int> dis(-9, 9);
int myNumber = dis(gen)

You are right in that there are 18 counting numbers between -9 and 9 (inclusive).

But the computer uses integers (the Z set) which includes zero, which makes it 19 numbers.

Minimum ratio you get from rand() over RAND_MAX is 0, so you need to subtract 9 to get to -9.

The information below is deprecated. It is not in manpages aymore. I also recommend using modern C++ for this task.

Also, manpage for the rand function quotes:

"If you want to generate a random integer between 1 and 10, you should always do it by using high-order bits, as in

j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));

and never by anything resembling

j = 1 + (rand() % 10);

(which uses lower-order bits)."

So in your case this would be:

int n= -9+ int((2* 9+ 1)* 1.* rand()/ (RAND_MAX+ 1.));

Anytime you have doubts, you can run a loop that gets 100 million random numbers with your original algorithm, get the lowest and highest values and see what happens.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!