Chris F Chris F - 1 month ago 14
C++ Question

Random number within range (range changes after each run)

I'm trying to make a guess my number program, with the computer guessing the number that I choose, I seem to have finally got it working except for the random number range, the high number works but the low number doesn't,

I guess I shouldn't be doing lowGuess=rand() but I have no idea what I should be doing instead, could somebody point me in the right direction please?

Also feel free to give me feedback on the rest of the code, this is my first attempt at writing something myself. (with a little reference material)

#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

using namespace std;

const int high = 100;
const int low = 1;
int lowGuess = 1;
int highGuess = 100;
int myNumber = 0;
int guess = 0;
int guesses = 0;
bool correct = 0;

int askNumber();
int askResponse();
int guessNumber();

int main()
{
askNumber();

do
{
guessNumber();
askResponse();
} while (correct == 0);
cout << "Yes!! I guesed your number in " << guesses << " guesses.";

return 0;
}

int askNumber()
{
cout << "\n\nEnter a number between " << low << " - " << high << ".\n\n";
cin >> myNumber;

if (myNumber < low || myNumber >high)
{
return askNumber();
}
}

int guessNumber()
{
srand(static_cast<unsigned int>(time(0)));
lowGuess = rand(); //im doing something wrong here with lowGuess
guess = (lowGuess % highGuess) + 1; //im trying to generate a random number between
cout << "\n\nMy guess is " << guess << endl; //the value of lowGuess and highGuess
guesses += 1; //highGuess is working as intended but lowGuess isn't

//printing values to see them working
cout << "low " << lowGuess << " high " << highGuess << endl;

return 0;
}

int askResponse()
{
int response;
cout << "\n\nIs my guess too high, too low, or correct?\n\n";
cout << "1. Too High.\n";
cout << "2. Too Low.\n";
cout << "3. Correct.\n\n";

cin >> response;
if (response < 1 || response > 3)
{
return askResponse();
}
else if (response == 1)
{
cout << "\n\nToo high eh? I'll take another guess.\n\n";
highGuess = guess; //altering the upper limit of random number range
}
else if (response == 2)
{
cout << "\n\nToo low eh? I'll take another guess.\n\n";
lowGuess = guess; //alteing the lower limit of random number range
}
else if (response == 3)
{
correct = 1;
}

return 0;
}

Answer

srand should be called only once, usually in main. If you call srand every time with the same seed then the next rand() will always be the same.

Change guessNumber function to

int guessNumber()
{
    guess = lowGuess + rand() % (highGuess - lowGuess);
    cout << "\n\nMy guess is " << guess << endl;    
    guesses += 1;                                   
    cout << "low " << lowGuess << " high " << highGuess << endl;
    return 0;
}

For example 20 + rand() % 50 will generate a number between zero to 20 to 70.