Please critique my code?

Hello! This is my solution to a problem in a book I'm reading. The question is as follows:

"2. Write a program that picks a number between 1 and 100, and then lets the user guess what the
number is. The program should tell the user if their guess is too high, too low, or just right.

3. Write a program that solves the guessing game from problem 2. How many guesses does your program need?"

So the following is really an answer to number 3.

Specifically, I would like any ideas on how to make it shorter, neater, more elegant, etc.

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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# include <ctime>
# include <cstdlib>
# include <iostream>

using namespace std;

//Random number function
int randRange (int low, int high)
{
    return rand() % (high - low + 1) + low;
}


int main()
{
    srand(time(NULL));
    //Random number is generated between 1 and 100
    int number=randRange(1,100);

    //First guess is always 50
    int guessNumber=50;

    //Guess attempts are counted from zero
    int guessAttempts=0;

    cout << "Guess what number I'm thinking of...it's between 1 and 100 (inclusive)." << '\n';

    cout << guessNumber << '\n';
    guessAttempts++;

    // While the random number does not equal the guess number, this loop runs
    while (number != guessNumber)
    {
        if (number > guessNumber)
        {
            // This number holds the number just before the number is too high
            // so that it averages out in the next condition
            int previousGuessNumber = guessNumber;

            // Add 25 until too high
            cout << "Too low..." << '\n';
            guessNumber = guessNumber + 25;
            cout << guessNumber << '\n';
            guessAttempts++;

            if (number < guessNumber)
                {
                    // While loops prevent the number from 'falling through'
                    // prematurely and resetting 'thought process'
                    while (number < guessNumber)
                    {
                    // Again, stores number for use in averaging in next condition
                    int previousGuessNumber2 = guessNumber;
                    cout << "Too high..." << '\n';
                    guessNumber = (guessNumber + previousGuessNumber) / 2;
                    cout << guessNumber << '\n';
                    guessAttempts++;

                    if (number > guessNumber)
                    {
                        // Repeat same general process until the algorithm is air-tight!
                        while (number > guessNumber)
                        {
                        int previousGuessNumber3 = guessNumber;
                        cout << "Too low..." << '\n';
                        guessNumber = (guessNumber + previousGuessNumber2) / 2;
                        cout << guessNumber << '\n';
                        guessAttempts++;

                        if (number < guessNumber)
                            while (number < guessNumber)
                        {
                            previousGuessNumber2 = guessNumber;
                            cout << "Too high..." << '\n';
                            guessNumber = (guessNumber + previousGuessNumber3) / 2;
                            cout << guessNumber << '\n';
                            guessAttempts++;

                        }
                        }
                    }

                }

        }
    }

        // When guess is too high
        // same general process, but number is divided by two until
        // 'averaging conditions' are met
        else if (number < guessNumber)
        {
            int previousGuessNumber = guessNumber;

            cout << "Too high..." << '\n';
            guessNumber = guessNumber / 2;
            cout << guessNumber << '\n';
            guessAttempts++;

            if (number > guessNumber)
                {
                    while (number > guessNumber)
                    {
                    int previousGuessNumber2 = guessNumber;
                    cout << "Too low..." << '\n';
                    guessNumber = (guessNumber + previousGuessNumber) / 2;
                    cout << guessNumber << '\n';
                    guessAttempts++;

                    if (number < guessNumber)
                    {
                        while (number < guessNumber)
                        {
                        int previousGuessNumber3 = guessNumber;
                        cout << "Too high..." << '\n';
                        guessNumber = (guessNumber + previousGuessNumber2);
                        cout << guessNumber << '\n';
                        guessAttempts++;//A bunch of while statements to keep the value from
                                        // falling through

                        if (number > guessNumber)
                            while (number > guessNumber)
                        {
                            cout << "Too low..." << '\n';
                            guessNumber = (guessNumber + previousGuessNumber3) / 2;
                            cout << guessNumber << '\n';
                            guessAttempts++;

                        }
                        }
                    }
               }

        }
    }
    }

    cout << "Correct!" << '\n';
    cout << "Number should be: " << number << '\n';
    cout << "# of guesses: " << guessAttempts << '\n';
}
Well if you want short and concise ways to do it then this is the way I did the problems.

Feel free to ask questions about the code.

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
52
53
54
55
56
57

//====================================================
// Answer To Number 3
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
    srand(time(NULL));
    int number = 0,guess = 0, numberOfTries = 0;
    bool match = false;

    while(!match)
    {
        number = (rand()%100) + 1;
        guess =  (rand()%100) + 1;
        numberOfTries++;
        match = (number == guess)? true : false;
    }
    cout<<"It took "<<numberOfTries<<" tries to get a match.";
    return 0;
}

//====================================================
// Answer to Number 2

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
    srand(time(NULL));
    int number = 0, guess = 0;
    bool match = false;

    number = (rand()%100) + 1;
    while(!match)
    {
        cout<<"Guess a number between 1 to 100 (inclusive): ";
        cin>>guess;

        match = (number == guess)? true : false;

        if (number>guess)
            cout<<"Too low. Try Again."<<endl;
        else if (number<guess)
            cout<<"Too high. Try Again."<<endl;
    }

    cout<<"Congratulations, you got it right!";

    return 0;
}
Your answer to the second problem I find to be too tedious for the question itself, but it all makes sense though and I appreciate the effort you put in but I do not think this is the response the book was looking for ;)
Last edited on
guatemala007 wrote:
Your answer to the second problem I find to be too tedious for the question itself, but it all makes sense though and I appreciate the effort you put in but I do not think this is the response the book was looking for ;)


He didn't supply an answer to the second problem here, so I'm not sure what you're going on about. Certainly his solution to the third problem, while not ideal, will take fewer "guesses" on average than yours.

@OP: Your algorithm is basically (a typical binary search:)

For a given range, split the range to determine what the guess should be.
If the guess is too high, reduce the upper limit of the range to one below the guess.
If the guess is too low, increase the lower limit of the range to one above the guess.
Repeat until the number is found.

Which might look something like the following in a more compact form:

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
#include <iostream>
#include <cstdlib>
#include <ctime>

unsigned calcGuess(unsigned mn, unsigned mx)
{
    unsigned guess = ((mx-mn) / 2) + mn ;
    std::cout << "Guessing " << guess << '\n' ;
    return guess ;
}

int main()
{
    std::srand(std::time(0)) ;
    const unsigned minVal = 1 ;
    const unsigned maxVal = 100 ;

    unsigned value = (std::rand() % (maxVal - minVal+1)) + minVal ;

    std::cout << "The random number is: " << value << '\n' ;

    unsigned minGuess = minVal ;
    unsigned maxGuess = maxVal ;
    unsigned guess  ;
    unsigned nGuesses = 1 ;


    while ( (guess = calcGuess(minGuess, maxGuess)) != value )
    {
        if ( guess > value )
        {
            std::cout << "\tToo high!\n" ;
            maxGuess = guess-1 ;
        }
        else
        {
            std::cout << "\tToo low!\n" ;
            minGuess = guess+1 ;
        }

        ++nGuesses ;
    }

    std::cout << "Found it in " << nGuesses << " guesses!\n" ;
}
Last edited on
closed account (30X1hbRD)
I found a youtube video that explained a lot. I have the code here :
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
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main() {
int gumballs;
int choices = 5;
int try1;
srand(time(0));
gumballs = rand() % 20 *3;
cout << "try and guess how many gumballs in " << choices  << " Tries!!!" << endl;
for (int i = 0; i < choices; i++){
cout << "Guess # "<< i+1 << ": "<< endl;
cin >> try1;
if (try1 != gumballs)
{ 
if (try1 > gumballs) {cout << "Too big. Go smaller" << endl;
}
else {
cout << "Too small. Go bigger." << endl; }}
else {
cout << "You got it! congratulations!!! The amount was " << gumballs << endl; system("pause"); return 0;
}
	}
cout << "You LOSE!" << endl;
cout << "The Answer was " << gumballs << endl;
system("pause");
return 0;}
Last edited on
Hey prince, just put the code in between (code) and (/code), but replace the parentheses with brackets.

Cire, I love that solution. Do you think you could tell me how you came to that? It's very clean and simple. However, I don't understand what the point of adding/subtracting 1 from guess is. Could you explain?
closed account (30X1hbRD)
Thanks for the pointer! I've finally figured that dang thing out.
I don't understand what the point of adding/subtracting 1 from guess is. Could you explain?

Since we know the guess is wrong, there is no reason to include the value of the guess in the next iteration.

e.g. if the guess is 75 and that is too big, then maxguess for the next iteration becomes 74. Likewise if the guess is 25 and that is too small, then minguess for the next iteration becomes 26.
Topic archived. No new replies allowed.