
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 10001112.
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;
}

> ( 1000 + rand() % 1112 );
Because you're adding 1000 to a random number between 0 and 1111.
For 10001112
( 1000 + rand() % 113 );

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;
}

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.
Many thanks in advance


int table[]={2,4,6,8,10}
int i = rand()%5;
int myRandomNumber=table[i];
thats one way there are many more.

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 :)

rand()%4 give a random number in range 03
1+rand()%4 therfore gives a number in range 14
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.

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


Huhhhhhhhh :) I see now
Many thanks :) :) :) :) :) :) :)
I am just not thinking right LOL

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
pleaseee help :( :( :(
many thanks in advance :) :) :)

Think about it  that set's only one above the one from before, so just do
(2 * (1 + rand() % 5)) + 1

or easier:
3 + 2 * rand()%5