Skip to main content
GameDev.net gamedev.net
🔒 Locked

simple C++ help please

Started by M0o Jul 8, 2011 at 4:50 PM 4 replies 2k views
Original Post
M0o
M0o
Hey, im new to C++ and learn it through a book, anyways iv been set a task to rewrite a game "guess my number" where i have to make the computer guess the users number but i get stuck in a loop and i cant see why its really bugging me and i know its going to be the silliest thing...



[size="1"]// Guess My Number
// The classic number guessing game

[size="1"]#include
#include
#include

[size="1"]using namespace std;

[size="1"]int main()
{

srand(time(0)); // seed random number generator

int theNumber;

cout << "\nPlease enter a number between 1-100 for the computer to guess: ";
cin >> theNumber;

int tries = 0, computerGuess;

do
{
int computerGuess = rand() % 100 + 1;

cout << "The computers guess: ";
cout << computerGuess;
++tries;

[size="1"] if (computerGuess > theNumber)
cout << " Too high!\n\n";

if (computerGuess < theNumber)
cout << " Too low!\n\n";

}while (computerGuess != theNumber);


[size="1"] cout << "\nThe computer got your number in " << tries << " guesses!\n";

[size="1"] return 0;
}

MichaelNett
MichaelNett
That's possible. You never make sure that the number entered by the user is actually in the range of numbers that the computer could guess (which is between 1 and 100).
Texus
Texus
This line is wrong:

int computerGuess = rand() % 100 + 1;

You are redefining computerGuess.
Inside the do loop it will be a number, but when checking if it is different from theNumber, it will be 0 again.

You should leave the "int" on that line.
TGUI, a C++ GUI for SFML
texus.me
M0o
M0o

That's possible. You never make sure that the number entered by the user is actually in the range of numbers that the computer could guess (which is between 1 and 100).


what do you mean? i tell the user to pick a number between 1-100 and the computer picks a random number between 1-100 but after the computer get the right number the loop dosent end.
M0o
M0o

This line is wrong:

int computerGuess = rand() % 100 + 1;

You are redefining computerGuess.
Inside the do loop it will be a number, but when checking if it is different from theNumber, it will be 0 again.

You should leave the "int" on that line.



ahhhh i see now thanxs alot i knew it would be something silly i just thought i would have to set as int but i see now why i dont. :)

thanx for the help
fastcall22
fastcall22
Just to clarify: The problem you're experiencing is called variable shadowing


#include <iostream>

using namespace std;

int main() {
int var = 1;
cout << var << endl;

do {
cout << var << endl;

int var = 2; // var shadows the "var" outside this scope
cout << var << endl;
} while ( false );

cout << var << endl;
}


Output:

1
1
2
1

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.