# quick question on random #'s

• 05-06-2005
Tsukasa
quick question on random #'s
well im not completely sure how this assigns the variable first_die a random number from 1 - 6..

Code:

const int x = 1;
const int y = 6;
int main()
{
time_t seconds;
time(&seconds);
srand((unsigned int) seconds);

int first_die = rand() % (y - x + 1) + x;
cout << first_die;
system("PAUSE");
return 0;
}

I understand that x gets a constant value of 1 and y gets a constant value of 6... but why does the higher value get - from the lower value + 1 and all of it + lower value. I dont know... im a bit confused =P

o yea, im not really positive with modulus as well....
• 05-06-2005
laserlight
rand() % 6 returns an integer between 0 and 5, inclusive.
Since you want the range to be 1 to 6 inclusive, you add 1 (i.e. x).
If you wanted the range to be 2 to 7 inclusive, you add 2.
But then x would be 2, and y would be 7, yet the size of the range (y - x + 1 = 7 - 2 + 1 = 6) remains the same.
• 05-07-2005
prog-bman
Here is some good stuff on random numbers
http://faq.cprogramming.com/cgi-bin/...&id=1073086407
• 05-07-2005
Tsukasa
ok, another question...

Code:

#include <cstdlib>
#include <iostream>
#include <time.h>

using std::cout;
using std::cin;
using std::endl;

unsigned const int high = 500000;
unsigned const int low = 100000;
int main(){
time_t seconds;
time(&seconds);
srand((unsigned int)seconds);

for (int x;;x++){
cout << rand() % (high - low + 100000) + low << endl;
system("PAUSE");
system("cls");
}
return 0;
}

can you explained to me srand()...
• 05-07-2005
CornedBee
rand does not really generate random numbers. It generates so-called pseudo-random numbers. Those are a really long sequence of numbers, but eventually they repeat.
The problem is that on each program run, the sequence starts at the same place, so the results of your program would be the same every time. That's why it's possible to seed the generator, i.e. to set it to a specific starting position in the sequence. srand does just that.
The generator is usually seeded with some timestamp. This ensures that your program, if run at different times, gives different results.