How can I make my program generate random number between two given integers ?

I use
srand ( time(NULL) );
x = rand() % i;

to generate numbers modulo i. But I can't figure out how to generate between two numbers, suppose 1 and 3.

Recommended Answers

All 10 Replies

Use the difference of the two numbers as the upper end of the range, then add the lower number:

x = lo + rand() % (hi - lo);

This assumes that lo isn't greater than hi. Also, strange things happen with negative numbers, so ideally the range would be positive.

x = lo + rand() % (hi - lo)

This gives random number between hi and lo ( if 1 and 4 are given, then either 1, 2, 3 are displayed. But my question is, if 1 and 3 are given then I want to display either 1 or 3, no number between them.

You have little choice but to either collect the numbers into an array (or other collection) and then randomly select from the array, or filter out any generated numbers that aren't the ones you want.

Maybe

x = rand() %2;
if (x == 0) x = 1;
    else    x = 3;

This works for me

srand(time(0));

x = 1+ (rand % 3);

the number after the % is the max number...

Hope it helps :)

Hope it helps :)

Probably not, since this was already suggested and rejected.

You should read the entire thread before posting.

I did this.

srand ( time(NULL) );

        int x = rand() % 10;

        if( x % 2 == 0 )
        {
            cout<<"3";
        }
        else
        {
            cout<<"1";
        }

It Worked. But is there any way I can do this within rand() ?

cout << ((rand() % 2) ? '1' : '3') ;

It Worked.

For 1 and 3, but one of your test cases for rejecting the range suggestion was 1 and 4 being "given". This suggests that the numbers are unknown input from a user or stream. If you'll only ever be given two numbers then this approach is valid, but if you have an unknown amount of unknown numbers in an unknown range, it gets tedious very quickly. In fact, this is a manual version of my suggestion to collect the numbers in an array and randomly select from the array.

But is there any way I can do this within rand() ?

Not unless you have control over the source code of rand(), which is extremely unlikely. I say unlikely rather than impossible because it's possible to write your own version of the standard library and replace the one that came with your compiler. I do this myself, but it's not a trivial project.

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.