# Random numbers

• 02-20-2002
Wiz_Nil
Random numbers
I got this program which I have pasted below is not behavouring as I would expect it to.

It works fine but the thing is that it is not displaying the random numbers in the range i want it to, which is 1000-1112.

When I run it I find that the numbers are outside of this range!
I have no idea why?????????

Could someone help me out :)
Many thanks :)

#include <iostream.h>
#include <iomanip.h>
#include <stdlib.h>
#include <time.h>

int main()
{
srand( time(0));

for ( int i = 1; i <= 20; i++ ) {
cout << setw( 10 ) << ( 1000 + rand() % 1112 );

if ( i % 5 == 0 )
cout << endl;
}

return 0;
}
• 02-20-2002
Govtcheez
> ( 1000 + rand() % 1112 );

Because you're adding 1000 to a random number between 0 and 1111.

For 1000-1112
( 1000 + rand() % 113 );
• 02-20-2002
Paro
i always to random numbers like this:

[CODE]
#include <iostream.h>
#include <stdlib.h>
#include <time.h>

const int HIGH = 10;
const int LOW = 1;

int main()
{
int num;
time_t seconds;
time(&seconds);
srand((unsigned int)seconds);

num = rand() % (HIGH - LOW + 1) + LOW; //that makes the random number between HIGH and LOW

cout<<num<<endl;

return 0;
}
• 02-20-2002
Wiz_Nil
How would I get a random number from the following set of numbers... 2, 4, 6, 8, 10.

I thought of do... (2 + rand() % 8);
but that doesn't work.

• 02-20-2002
Govtcheez
2 * (1 + rand() % 4)
• 02-20-2002
Stoned_Coder
int table[]={2,4,6,8,10}
int i = rand()%5;
int myRandomNumber=table[i];

thats one way there are many more.
• 02-20-2002
Wiz_Nil
Could you please explain this to me.

From what I understand, the above code is saying that the range is from 0 to 4, but than multiply by 2.

Are you sure it is multiply, shouldn't it be plus?

I don't kmow, can u please explain :)
• 02-20-2002
Stoned_Coder
rand()%4 give a random number in range 0-3
1+rand()%4 therfore gives a number in range 1-4
now 2*1=2
2*2=4
2*3=6
2*4=8

unfortuneately it doesn't make 10 lol but you can figure out how to now i'm sure.
• 02-20-2002
Govtcheez
Well, first of all, it should be 5, not 4 (I don't know what I was thinking).

rand() % 5 gives a random numbe between 0 and 4
Adding 1 puts it between 1 and 5
Multiplying by 2 gives eitehr 2, 4, 6, 8, or 10
• 02-20-2002
Govtcheez
Concurrency again...
• 02-20-2002
Wiz_Nil
Huhhhhhhhh :) I see now

Many thanks :) :) :) :) :) :) :)

I am just not thinking right LOL
• 02-20-2002
Wiz_Nil
what if i want random numbers from a set of, 3,5,7,9,11

I thought about 2*(3+rand()%8) but that's wrong
than i thought.....
2*(3+rand()%8)-1 but that's wrong too