C++ Why does this variable return a random value?
c++, int, random
Solution
You have not initialized some variables that you then use before assigning any value to them. They start with an unspecified value, which looks random. You can fix it like this
int guess = 0;
int guesses = 0;
Problem
I have made a basic "guess my number game" in c++, and I have added a variable for how many guesses it took the person to guess the number. However when the game ends, a random value for the guesses is shown. Something like 1980046322. I can't figure out why it does this, considering that I haven't put anything extraordinary into my code. ``` #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { int randomNumber; int guess; int guesses; srand((unsigned)time(0)); randomNumber = (rand()%10)+1; cout << "I am thinking of a number between 1 to 10. Can you guess it?" << endl; while(guess != randomNumber){ cout << "That is not correct, try again."; guesses++; cin >> guess; } if(guess == randomNumber){ cout << "Good Job. Guesses: " << guesses << endl; guesses++; } return 0; } ```