Random # not really random

Dice simulation giving same output repeatedly

Page 1 of 1

2 Replies - 562 Views - Last Post: 12 December 2010 - 11:24 PM Rate Topic: -----

#1 graveyardrave  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 22-September 10

Random # not really random

Posted 12 December 2010 - 07:50 PM

Hello to everyone. Been working on this random dice roll simulation longer than I should have.

I've got a function that returns a random # 1-6 (to simulation the roll of a die)
It's supposed to roll 100 times, and output the number of each roll.
I initialized an srand, to get a truly random #, but it's not giving me a random # for each roll. Instead, it randomizes the first roll, then appears to repeat that #, till reaching 100.

here's what I've got
#include <iostream>
#include <iomanip>
#include <ctime>

using namespace std;

int dieRoll();

int main ()
{
	int x = 1; // this is my counter
	
		
		do { // let's get things rolling
			srand(static_cast<int>(time(0)));
			cout << " " ;
			cout << "#" ;
			cout << x;
			cout << ": " ;
			cout << dieRoll();
			x += 1;
		} while (x < 101); // end do while loop	

system("pause");
return 0;
}

//***** Function definition *****//

int dieRoll()
{	
	int roll = 0;	
	roll = 1 + rand() % (6 - 1 + 1);
	return roll;
}



Did I do something wrong with the srand?

Is This A Good Question/Topic? 0
  • +

Replies To: Random # not really random

#2 Salem_c  Icon User is online

  • void main'ers are DOOMED
  • member icon

Reputation: 1678
  • View blog
  • Posts: 3,180
  • Joined: 30-May 10

Re: Random # not really random

Posted 12 December 2010 - 10:34 PM

Yes, you called it more than once.

More specifically, you called it in a loop!

> srand(static_cast<int>(time(0)));
Your loop takes microseconds to execute. time() ticks along in seconds.
As far as your program is concerned, the result is a constant, and you effectively have something like.

srand(42);

So yes, your rand() will produce the same result each time.
Was This Post Helpful? 2
  • +
  • -

#3 graveyardrave  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 22-September 10

Re: Random # not really random

Posted 12 December 2010 - 11:24 PM

Yes, I see now. Thank you.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1