Higher or Lower Game Help
Apr 18, 2014 at 7:56pm UTC
I was wondering if someone could point out where im going wrong, the random number the computer is generating isn't within the limits that are being dynamically set
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
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
srand(time(0));
cout << "Welcome to Higher or Lower" << endl;
cout << "Please pick a number between 0 and 100" << endl;
system("PAUSE" );
int high = 100, low = 0, guess;
char resp;
while (resp!='Y' ){
guess = (rand() % high + low);
cout << endl << "Is your number :" << guess << endl;
cout << "Yes - Y. Higher - H. Lower - L: " ;
cin >> resp;
if (resp=='H' ){
low = guess;
}else {
high = guess;
}
}
return 0;
}
thanks in advance for any help
Apr 18, 2014 at 7:58pm UTC
guess = (rand() % high + low);
guess = (rand() % (high - low) + low);
Last edited on Apr 18, 2014 at 7:58pm UTC
Apr 18, 2014 at 8:02pm UTC
Thanks that fixed it, could you possibly explain why that works so i know in future?
Apr 18, 2014 at 8:07pm UTC
for example high = 60, low = 50;
your code:
rand() % high
generates number 0 - 59
(rand() % high + low)
generates 50 - 109
My code:
generates 0 - 9
(rand() % (high - low) + low);
generates 50 - 59
high - low is a "distance" between two numbers, amount of numbers between them. we should be able to generate that "dinstance" amount of different values, no more, no less.
+ low just modifies it to be in needed range.
Apr 18, 2014 at 8:10pm UTC
Ok, thanks
Topic archived. No new replies allowed.