user3440271
user3440271

Reputation: 1

Number guessing game with illogical bug

#include <iostream>
#include <cstdlib>
#include <windows.h>

using namespace std;
srand(time(NULL)); 

int main(){
    int botguess;
    int playerinput;
    int mi=1, ma=100;
    int turns = 0;
    cout<<" what do you want guessed:";

    cin>> playerinput;
    cout<< "time for me to start guessing\n";

    for(int i = 0;i < 50;i++) {
        botguess = rand() % ma + mi;

        if(playerinput > botguess){  //<--the problem 
            mi = botguess;
        }

        if(playerinput < botguess) {
            ma = botguess;
        }

        cout<<"Max:"<<ma<<"\n"<<botguess<<"\n";
        Sleep(1000);
        if(botguess == playerinput)
        {
            cout<<"you win";
        }
    }

    cin.get();
    return 0;
}

So I've been tearing my hair out about why logically this doesn't work. This is a program that is supposed to guess the players number quickly but not instantly. The program doesn't perform like it looks.

The line that I noted causes a bug where the max number possible is being ignored. im getting number that are 100+ but under 200 and i don't know why. When I remove the lines concerning the mi variable nested in the statement in the for loop. The program doesn't go over 100 but I don't get the other end of the program solving the player number.

Also if you figure it out can you please explain it to me I don't just want a answer.

Upvotes: 0

Views: 77

Answers (2)

Bradley Thomas
Bradley Thomas

Reputation: 4097

The problem you are having is caused by the fact that mi is set to botguess, which can easily be greater than zero, then on the next cycle if ma is still 100 (or anywhere near it), you're going to sometimes get numbers greater than 100 set into botguess.

Edit added: the % operator in C++ is mod division (ie. gives the remainder of integer division) So for example, 98 % 100 + 15 will be 98 + 15, i.e. 113

This link may help you:

http://www.cplusplus.com/reference/cstdlib/rand/

Upvotes: 1

Amadan
Amadan

Reputation: 198324

botguess = rand() % (ma - mi + 1) + mi

You don't want ma different numbers, you want much less of them. Look at an example: (5..10) contains 6 different numbers: [5, 6, 7, 8, 9, 10]; but if you do rand() % 10 + 5, you're getting numbers from 5 (5 + 0) to 14 (5 + 9). What you need is rand() % 6 + 5, where 6 is 10 - 5 + 1.

Upvotes: 2

Related Questions