Generating a random number with a set non-zero minimum

Feb 19, 2013 at 4:55am
Hey guys,
I have to create a program that guesses the user's age.
The user has to enter X, if the computer guessed the right age.
If they are younger than the guessed age, they are to type Y, and the program will keep looking for random numbers with the first guess as the max value.
So if the initial guess is g1.
If the user enter 'Y' the program will guess a second guess g2, where:
g2= rand() %g1 +1;

Now what happens if the user is older than the computer's initial guess?
what should i set g2 to be?


In short, what I wanna do is let the program find a random number between a non-zero minimum and a maximum.
Last edited on Feb 19, 2013 at 5:00am
Feb 19, 2013 at 5:46am
If yo want to generate number in range [a, b] you should do:
1
2
c = b - a + 1;
random_n = rand() % c + a
Feb 19, 2013 at 5:51am
So if I want a to be the number that a user enters say: "g1"
and b to be "128" at all times.

c = 128 - g1 +1;

I should write

random_n = rand() % 128 - g1 + 1 + g1

won't that be the same as:

random_n = rand() % 128 +1
?
Feb 19, 2013 at 6:58am
it will be (rand() % (128 - g1 + 1)) + g1
I have added a couple of parentheses to show you order of operations. Because 2 * (2 + 2) isn't equal to 2 * 2 + 2
Topic archived. No new replies allowed.