1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Random number generator help

Discussion in 'C++' started by kjt1991, Oct 30, 2010.

  1. kjt1991

    kjt1991 New Member

    Joined:
    Oct 30, 2010
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    Hey I am currently trying to write a program that has the user enter a value and then this becomes the max value for the generator. So if the user enters 10 the generator picks a number between 1 and 10. The next step is the user has to guess the value the generator picks. My problem lies in every time I use the number 10 as the maximum value the generator always picks the number 8. I need help trying to figure out how to make the maximum value 10 and then have the generator pick different values every run through. The number 8 the first run through, the number 2 through the 2nd run through and the number 6 on the first run through. These previous numbers are made up and the program doesn't have to run any of these previous picked numbers just in case I wasn't clear early. Any help would be appreciated. Thank you.
    Code:
    #include <iostream>
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    using namespace std;
    
    int main ()
    {
    	int x,guess;
    	cout << "Enter a maximum value" <<endl;
    	cin >> x;
    	cout << "Your number is between 0 and "<< x << endl;
    	x = rand()%(x + 1);
    	srand(time(NULL));
    	
    	cout << "Enter your guess" <<endl;
    	cin >> guess;
    	while ( guess != x)
    	{
    		
    		cin >> guess;
    	
    	
    		if (guess > x)
    		{
    			cout << "Guess lower" <<endl;
    		}
    
    		else if ( guess < x )
    		{
    			cout << "Guess higher" <<endl;
    		}
    		else 
    		{
    			cout << "Congratulations you guessed the correct value" << endl;
    		}
    	}
    	
    		
    	system("PAUSE");
    	return 0;
    }
    
     
  2. virxen

    virxen New Member

    Joined:
    Nov 24, 2009
    Messages:
    387
    Likes Received:
    90
    Trophy Points:
    0
    reverse this 2 lines
    from
    to
    Code:
        srand(time(NULL));
        x = rand()%x + 1;
     
    Last edited: Oct 30, 2010
    shabbir likes this.
  3. kjt1991

    kjt1991 New Member

    Joined:
    Oct 30, 2010
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    thank you so much I didn't even think about reordering the lines.
     

Share This Page