|
-
Jun 22nd, 2002, 02:24 PM
#1
Thread Starter
Addicted Member
Problem with random number generator
This code keeps giving me the same random number, can somone please tell me why?
{
int RandomNumber;
int i;
int j;
for (i = 0; i < SCREEN_HEIGHT; i++) /*For the number of rows on the console*/
{
for (j = 0; j < SCREEN_WIDTH; j++)/*For the number of columns on the console*/
{
//Sleep();
srand(time(NULL));
RandomNumber = 1 + (int) (3.0 * rand() / (RAND_MAX + 1.0));
switch (RandomNumber)
{
case 1 : write_char('1');
break;
case 2 : write_char('0');
break;
case 3 : write_char(' ');
break;
}/*switch (random_number)*/
}
}
}
-
Jun 22nd, 2002, 03:03 PM
#2
Fanatic Member
Not sure...this code works fine for me. One thing that could make it screw up though is you only need to do srand() once.
Code:
#include <iostream>
#include <ctime>
using namespace std;
const SCREEN_HEIGHT = 25;
const SCREEN_WIDTH = 80;
int main()
{
srand(time(NULL));
int RandomNumber;
int i;
int j;
for (i = 0; i < SCREEN_HEIGHT; i++)
{
for (j = 0; j < SCREEN_WIDTH; j++)
{
RandomNumber = 1 + (int)(3.0 * rand() / (RAND_MAX + 1.0));
switch (RandomNumber)
{
case 1:
cout << 1;
break;
case 2:
cout << 0;
break;
case 3:
cout << ' ';
break;
}
}
}
return 0;
}
Alcohol & calculus don't mix.
Never drink & derive.
-
Jun 23rd, 2002, 01:54 AM
#3
New Member
quick beginner question
how would you change the above code to include numbers an letters. like say you entered : 1m4j3js52 : and wanted that randomized?
-
Jun 23rd, 2002, 05:13 AM
#4
I don't see a duplicate srand() call, unless you edited your post 
Your code and Wynd's code both work.
The real isssue is the fact that you are choosing only three random values. It's not far out of consideration to think that you could have three calls returning the same value.
I know when I wrote my first random number generator a long time ago, we were testing it and thought it had a problem for the same reason you see. It kept repeating the same value. But we were only choosing 4 values.
-
Jun 23rd, 2002, 09:22 AM
#5
Fanatic Member
Wynd meant that, because the srand was inside the for-loops, the randomizer always initializes with the same seed. The loop is executed within one second, so the time, used as a seed, didn't change.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|