Number Guessing Game (Constant Ints Problem)

I need to initialize a set tries count as a constant value and implement it into the game as the max amount of tries for the game. Any help is appreciated. Thanks

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
40
41
42
43
44
45
46
47
48
49
50
51
#include <cstdlib>
#include <time.h>
#include <iostream>
using namespace std;
void printGreeting();
void game();
void printGoodbye();
int main()
{
	printGreeting();
	srand(time(0));
	char answer;
	do{
	game();
	cout << "Would you like to play again? (Y/N)" << endl;
	cin >> answer;
	}
	while(answer == 'Y' || answer == 'y');
	printGoodbye();
	return 0;
}

void game(){
	int const number = rand() % 50 + 1;
	int const tries = 10;
	int guess;
	do
		{
			cout << "Enter your estimate: ";
			cin >> guess;
			if (guess < number)
				cout << "TOO LOW!!" << endl;
			else if (guess > number)
				cout << "TOO HIGH!!" << endl;
			else
				cout << "Your guess is right!" << endl;
	    }
		while (guess != number);
}

void printGreeting(){
	cout << "Hello and welcome to this number guessing game." << endl;
	cout << "In this program you will be asked to guess a number from the given range in the amount of tries given to you by me" << endl;
	cout << "You will guess from a range of 1-50 and will be given 10 tries." << endl;
}

void printGoodbye()
{
	cout << "Thanks for playing my game!" << endl;
	cout << "Good-bye and have a nice day!" << endl;
}
Last edited on
You would need a variable to keep track of the number of tries that the user has used.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void game()
{
    int const number = rand() % 50 + 1;
    int const max_tries = 10;
    int guess, tries = 0;
    do {
            cout << "Enter your estimate: ";
            cin >> guess;
            if (guess < number)
                cout << "TOO LOW!!" << endl;
            else if (guess > number)
                cout << "TOO HIGH!!" << endl;
            else
                cout << "Your guess is right!" << endl;
            tries++;
    } while (guess != number && tries < max_tries);
}
Last edited on
Line 25: Don't have tries as a const int, instead leave it as a int value.
After the if and else if statement, decrease the tries by 1 tries--
The while condition should be while (tries>0&&guess!=number)
Last edited on
Topic archived. No new replies allowed.