Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Random number generator help (http://www.go4expert.com/forums/random-generator-help-t23720/)

kjt1991 31Oct2010 01:28

Random number generator help
 
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;
}


virxen 31Oct2010 02:06

Re: Random number generator help
 
reverse this 2 lines
from
Quote:

x = rand()%(x + 1);
srand(time(NULL));
to
Code:

    srand(time(NULL));
    x = rand()%x + 1;


kjt1991 31Oct2010 04:08

Re: Random number generator help
 
thank you so much I didn't even think about reordering the lines.


All times are GMT +5.5. The time now is 19:08.