Random number guessing game

I'm supposed to come up with a code to have the person give a max value and then guess the number within that max value, with the result being too high or too low until they guess the number. This is the code I have so far. There's more to the assignment, but I'm just trying to get this part to work for now.

#include <iostream>
#include <time.h>
#include <stdlib.h>

using namespace std;

int main()
{
int max;
cout << "How many random numbers?";
cin >> max;


srand( (unsigned) time(0) );

int value;
value = rand() % max + 1 ;
max -= 1;

cout << "Enter your guess: ";
int guess; cin >> guess;


if (guess == value)
cout << "YOU WIN!" << endl;

else if (guess != value)

do
{
if (guess <= value)
{cout << "Too low" << endl;
cout << "try again: ";
int guess; cin >> guess;}

else if (guess >= value)
{cout << "Too high" << endl;
cout << "try again: ";
int guess; cin >> guess;}

} while (guess != value);


cin.get();
cin.get();

return 0;
}


The problem is, when I run the code, if the first value entered is too high, all numbers after will result in "too high" and vice versa. Is there an easy way around this?
Here you run into this problem becouse you declare int guess twice ( in lines 21 and 34 ), so when in line 34 you cin >> guess that changes the local guess variable.
If you removed all guess declarations except the first one, this problem should go away.
Though overall your design has flaws. Now you can only win if you guess correctly the first time.
it should be more like..

after you calculate value
1
2
3
4
5
6
do{
    ask for a guess,
    if guess > value write 'too high'
    if guess < value write 'too low'
    if guess == value write 'you win'
}while(guess != value)
Topic archived. No new replies allowed.