Hi, I am trying to generate a random number, and then the user guesses it. Once the user guesses the right number, the program generates another random number and asks the user again. and the user presses zero to exit the program. the trouble i am having is generating a new random number after the user guesses the right number, here is my program:
int main()
{
//srand((unsigned)time(0));
//double avg = rand();
//int div = rand(10);
//cout << avg << endl;
srand(time(NULL));
//srand(time(0));
int random_integer = rand()%10+1;
int numberGuess, tracker, question = -1, correctGuess = 0, incorrectGuess;
cout << "Welcome to the number guessing game.\nFor each game, you have at most 3 chances to guess a secret number from 1 to 10."<< endl;
cout << random_integer << endl;
while (numberGuess!=0){
for (tracker = 0; tracker <3; tracker++){
cout << "Enter a number from 1 to 10. Enter 0 to exit:"<< endl;
cin >> numberGuess;
question = question + 1;
if (numberGuess == 0 || numberGuess < 0|| numberGuess>10){
break;
}
else if ( numberGuess == random_integer){
cout << "Congratulation, correct! Let’s start a new secret number." << endl;
correctGuess = correctGuess+1;
//srand((unsigned) time(0));
//rand()%10+1;
//sleep(10)
int random_integer = rand()%10+1;
cout << random_integer << endl;
break;
}
else if ( numberGuess != random_integer && tracker == 0){
cout << "Please try agian, you have 2 trys left" << endl;
}
else if ( numberGuess != random_integer && tracker == 1){
cout << "Please try agian, you have 1 trys left" << endl;
}
else if ( numberGuess != random_integer && tracker == 2){
cout << "Not correct. You have reached your third trials. The correct number is " << random_integer << endl;
}
}
cout << random_integer << endl;
tracker = 0;
In the code snippet above, you make a new variable on line 7 with the same name as an already existing variable and assign a random value to it. That variable ceases existing on line 10. The other variable of the same name remains unchanged.