I am having a problem with my code for an assignment. I am to take the a dice and roll it 100 times, output the random results, and then ask the user if they would like to roll it again. My only problem is the second and subsequent times the die is rolled, it is no longer random. I have tried placing the rand operator in different places in the code but still am lost. here is my code. Any help would be apreciated.

#include "stdafx.h"
#include "iomanip"
#include "iostream"
#include "ctime"
using namespace std;

int dieRoll ();

int _tmain(int argc, _TCHAR* argv[])
{


//Intialize Variables

	int sideOne=0;
	int sideTwo=0;
	int sideThree=0;
	int sideFour=0;
	int sideFive=0;
	int sideSix=0;
	int counter=0;
	int dieUp=0;
	char die=' ';

//Rand operator
srand(static_cast<int>(time(0)));

//User input
	cout<<"Do you want to roll the die (y or n):";
	cin>>die;
	die = toupper(die);

while (die !='N')
{

//Dice calculations
while(counter<100)


{dieUp=dieRoll();
counter=counter+1;

switch (dieUp)
{
case 1: sideOne=sideOne+1;
	break;
case 2: sideTwo=sideTwo+1;
	break;
case 3: sideThree=sideThree+1;
	break;
case 4: sideFour=sideFour+1;
	break;
case 5: sideFive=sideFive+1;
	break;
case 6: sideSix=sideSix+1;
	break;
}
}
//Output
cout<<"The number one was rolled "<<sideOne<<" times"<<endl;
cout<<"The number two was rolled "<<sideTwo<<" times"<<endl;
cout<<"The number three was rolled "<<sideThree<<" times"<<endl;
cout<<"The number four was rolled "<<sideFour<<" times"<<endl;
cout<<"The number five was rolled "<<sideFive<<" times"<<endl;
cout<<"The number six was rolled "<<sideSix<<" times"<<endl;
cout<<endl<<endl;
cout<<"Do you want to roll the die (y or n):";
	cin>>die;
	die = toupper(die);


}
system ("pause");
	return 0;
}

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

Recommended Answers

All 6 Replies

What do you mean saying its no longer random? Are you getting the same results each time?

Yes after the first loop, when the user enters "y" to repeat the loop; the next(and any subsequent) set of results is the same as the first. However, if I restart the program, the results are random each time.

What happens if you move your srand call on line 26 to line 35?

There is no change. Still returning same values after first loop. I also tried moving it to line 70, and tried resetting dieUp=0 on line 70 with no changes.

You need to reset the counter on or about line 36. Otherwise you are just skipping your while loop each time (you will want to reset your counts around the same point).

Minor point, but int should be unsigned on line 26.

commented: Nice spot +4

That was my problem. I had tried resetting the wrong variable. Thank you very much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.