Hello,

I am trying to figure out how to get the rand() function to include 0.

int value = rand() % range + 1;

No matter what I set range to be, the lower bound is always 1.

That's because your code is wrong. rand() function always include 0:

int value = rand() % (range + 1);

Remove the "+1" please.

int value = rand() % range;

rand() returns a integer between 0 to RAND_MAX.

Also, make sure that you use srand() before the calling, or you may get the same each running time.

http://www.becoding.com/source/rand/

Hello,

I am trying to figure out how to get the rand() function to include 0.

int value = rand() % range + 1;

No matter what I set range to be, the lower bound is always 1.

Hello,

I am trying to figure out how to get the rand() function to include 0.

int value = rand() % range + 1;

No matter what I set range to be, the lower bound is always 1.

You have the right basic idea, but you've not delineated your code correctly. As written, your code generates a random integer from 0 to (range-1), then adds (1) to that result. Thus, when it does generate a random 0, it bumps that 0 to a 1.

You need to include the "+ 1" with the range to prevent this behavior:

int value = rand() % (range + 1);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.