Number Guessing Game not Working for Negative Numbers

Hey there -- trying to write a program that allows the player to pick a number, and then tells them if it's too low or too high until they get the right answer. When they have the right answer, the program should tell them how many tries it took. My code so far is below. It works for positive numbers, but if the user picks a negative number, the loop breaks prematurely and gives the wrong answer about attempted guesses.

Can't seem to pinpoint the issue here.

Any help is greatly appreciated!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 #include<iostream>
using namespace std;

int main ()
{
   int n, count=1;
   int guess;

   cout << "Enter the number for the player to guess. " << endl;
   cin >> n;

   cout << "Enter your guess. " <<endl;
   cin >> guess;

   do
   {
       if (guess>n)
           {
           cout << "Too high-try again. " << endl;
           cin >> guess;
           }

       if (guess<n)
           {
           cout << "Too low-try again. " << endl;
           cin >> guess;
           }

       else
           {
           cout <<"You guessed it in " << count << " tries.";
           break;
           }

           count++;
           } while(1);

     return 0;
} 

Last edited on
Hi and welcome to this forum. Please edit your post and use code tags for all of your code - http://www.cplusplus.com/articles/jEywvCM9/

Your if statements will mess up the program and end it when it shouldnt, here is why.

Let's say n = 55;

My first Guess is 66. First if-statement is entered because 66 is bigger than 55. Inside that if-statement I can guess again. I pick 66 again. Now it checks if guess is smaller than n, which it's not. So it goes to the else statement and it ends. That's not what we want is it?

Change the middle if-statement to and else if statement.

else if (guess<n)

to avoid that problem.

Edit 1:

Instead of having 2 different cin >> guess; You could simply just have one at the top of the do-while loop, which would allow you to remove the ones inside the if statements and the one above the do-while loop. And the program would do the exact same thing.
Last edited on
Thanks for the flag -- edited my post.

And thank you for the feedback.
Also I should mention that I never had the problem you described, It worked perfectly fine with negative numbers and Im having a hard time seeing why it would break prematurely for you. Try to make these changes I told you about and see if it fixes it.
Last edited on
Topic archived. No new replies allowed.