I created this code to make a guess number game, I noticed that whenever I type in "y' to play again the random number is the same as the previous one. Is there a way I can make it a random number every time I enter 'y'? (I am very new to this) What should I change to generate a random number every time?
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(void)
{
srand((unsigned)time (0));
int number = rand() % 10 + 1;
int guess;
char answer = 'y';
{
while (answer != 'n')
{
cout << "Guess a number 1-10: ";
cin >> guess;
while (guess != number)
{
if (guess > number)
{
cout << "Too high, guess lower: ";
cin >> guess;
}
else if (guess < number)
{
cout << "Too low, guess higher: ";
cin >> guess;
}
}
if (guess == number)
{
cout << "Correct! You guessed the number\n";
}
do
{
cout << "Guess again? y/n:";
cin >> answer;
} while (answer != 'y' && answer != 'n');
}
Should put your code inside code brackets, [.code] [./code] (without the periods).
Personally, I don't like the way the program is implemented. If you want to make it use a new number every time, then simply change the number once they win in the if statement, like this:
1 2 3 4 5
if (guess == number)
{
cout << "Correct! You guessed the number\n";
number = rand() % 10 + 1;
}