c++ - Random number generator not generating within set variable parameters -


forgive me if simple question, i'm extremely new coding, i've been trying create program in user thinks of number , computer tries guess using parameters on random number generator.

#include <iostream> #include <cstdlib> #include <ctime> #include <string>  using namespace std;  int main() {     srand(static_cast<unsigned int>(time(0))); //seed random number generator     int guess = (rand() % 100) + 1; //random number between 1 , 100     int turns = 1;     int max = 100;     int min = 1;      cout << "pick number between 1 , 100 press enter." << endl;     cin.get();      string responce = "n";     cout << "was " << guess << " number? y/n" << endl;     cin >> responce;      while (responce == "n" || responce == "n")     {         ++turns;          string lowresponce;         cout << "was number low?" << endl;         cin >> lowresponce;          if (lowresponce == "y" || lowresponce == "y")         {             min = guess; //this statement should (?) set minimum number whatever guessed.             guess = (rand() % max) + min; //then should calculate number between minimum (which last number guessed) , maximum         }         if (lowresponce == "n" || lowresponce == "n")         {             max = guess;             guess = (rand() % max) + min;         }          cout << "was " << guess << " number? y/n" << endl;         cin >> responce;     }      cout << "i guessed number, " << guess << ", in " << turns << " turns!" << endl;      return 0; }     

occasionally, number generate out of set parameters, so, , life of me cannot understand why.

results of test run:

number = 60

1st guess = 72, max set 72

2nd guess = 39, min set 39

3rd guess = 45, min set 45

4th guess = 99, out of range, (45,72), , shouldn't have been guess in first place.

any ideas why happening?

think of it, chose 60, computer guesses 30. set min = 30 (correctly), , want range (30,100]. should set :

guess = (rand() % (max - min)) + min; 

same calculation greater guess

edit: improve code, suggest learn do while, might :)


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -