#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <windows.h>
usingnamespace std;
int main()
{
srand(time(0));
bool numRight = false;
int hint;
int logic;
int high = 100;
int low = 1;
cout << "Think of a number between 1 and 100 and I'll guess what it is!\n"; Sleep(6000);
while(numRight == false){
logic = rand() % high + low;
cout << "Is the number you're thinking of " << logic << "?\n";
cout << "1. Yes\n2. Too high\n3. Too low\n";
cin >> hint;
if(hint == 1){
cout << "Haha! I knew it! In your face!\n";
numRight = true;
}
elseif(hint == 2){
high = logic;
}
elseif(hint == 3){
low = logic;
}
}
}
and for some reason, the random number being generated will go above the 'high' variable, when it's not supposed to. What am I doing wrong?
I'm a total newbie to programming just had a few college courses so I could be wrong but i'll take a stab at line 22, "logic = rand() % high+ low;" the way i read that you are adding high and low var, which would give you a random number out of 101? try inputting rand() %100 instead .... like i said just a guess trying to learn this stuff myself.
Let's say for example low is 25 and high is 70. The expression rand() % high will return a number between 0 and 69. Let's say rand() was such that 69 was returned. 69 + 70 is 139 which is greater than 70.
In the above example, instead of a number between 0 and 69 being returned from the mod, you would actually want a number between 0 and 45 (the difference between 70 and 25) to be returned, as this number when added to 25 will be maximized at 70. Thus in this example you would want the expression to be rand % 46 + 25. 46 in this case is (high - low + 1).
That's a bit weird. I thought rand() % high + low was supposed to return a value between those two numbers? Why does it return a value between the two defined values then add the high variable to it?
Because that's how modulus and addition are defined.
X % Y (X mod Y) returns the remainder of X / Y, which effectively gives you a number between 0 and Y-1.
Hence the expression you have given first calculates rand() % high, giving you a number between 0 and high-1, then adds low, resulting in a range between 0+low and high-1+low.