srand()

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • makita18v
    New Member
    • Oct 2008
    • 7

    srand()

    So I've fixed pretty much all of my problems for my program which is supposed to seed the random number generator for rolling two dice. My program compiles, but I cannot get the random numbers to happen, and I've tried several different things. I've included all of my code, but really the only thing I can't get to work right is the random number generator, so any help would be great.

    Code:
    #include <iostream>
    #include <string>
    #include <cstdlib>
    #include <ctime>
    const int SIX = 6; 
    
     using namespace std;
     int main ()
     {
    	 int seed = (int)time(0);
    	 srand(seed);
    	 char gamePlay;
    	 char playAgain;
    	 char notAgain;
    	 char yesSir;
    
    	 cout << "Do you want to roll the dice?\n";
    	 cout << "Enter y or n: ";
         cin >> gamePlay;
    	 cin.ignore( 80, '\n' );
    	switch (gamePlay)
    	{
    		case 'y':
    		case 'Y':
    			break;
    		case 'n':
    		case 'N':
    			cout <<"Have a nice day." << endl;
    		    system("PAUSE");
    			return 'E';
    		default:
    			cout <<"Invalid input, please re-enter!" << endl;
    			system("PAUSE");
    			return 'E';
    	}
    		 do
    		 {
    			 int d1 = 1 + seed % SIX; 
    		     int d2 = 1 + seed % SIX;
    		     if (d1 == 6 && d2 == 6) 
    			 	cout <<"You rolled boxcars\n";
    			 if (d2 == 1 && d2 == 1) 
    			 	 cout <<"You rolled snake-eyes\n";
    			 else 
    				cout <<"You rolled " << d1 << " and " << d2 <<endl;
    				cout << "Do you want to play again?\n";
    				cout <<"Enter y or n: ";
    				cin >> yesSir;
    				cin.ignore( 80, '\n');
    				
    			switch (yesSir)
    			{
    				case 'y':
    				case 'Y':
    					break;
    				case 'n':
    				case 'N':
    					return 'N';
    					break;
    				default:
    					cout <<"Invalid input, please re-enter!" << endl;
    					system("PAUSE");
    					return 'E';
    			}
    
    		 }while (yesSir != 'N');
    
    	 system ("PAUSE");
    	 return 0;
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    seed is not a random function. It is not a random number. seed is an int that you told to be the value of time(0).

    To get random numbers, use the rand() function.

    Comment

    • Tassos Souris
      New Member
      • Aug 2008
      • 152

      #3
      You can write this for example:
      Code:
      /* At the beginning of your program */
      srand( (unsigned int)time( NULL ) );
      
      /* more lines here */
      int randomNumber = rand();
      The above is how to combine the srand() and rand() functions.

      To take a random number in the range of [ 1, 6 ]:
      Code:
      int dieFaceValue = 1 + rand() % 6;

      Comment

      Working...