OK I need to create an even random number between 54 and 212 inclusive. The only catch is that it has to be done in a single statement. I have a class to generate random number within a range, but like I said, I want to do it in a single statement. I came up with this, but it's not working correctly. Any ideas?
int main()
{
srand( time(NULL));
int i;
i = (rand() % 106) * 2;
cout << i;
return 0;
}
Nick
2,8454 gold badges30 silver badges40 bronze badges
asked Aug 1, 2010 at 18:52
-
Is this some kind of a homework?Darin Dimitrov– Darin Dimitrov2010年08月01日 18:55:10 +00:00Commented Aug 1, 2010 at 18:55
-
Why do you want to do this in a single statement? Is this homework?kerkeslager– kerkeslager2010年08月01日 18:56:07 +00:00Commented Aug 1, 2010 at 18:56
1 Answer 1
Generate any number in the interval [27, 106]
and multiply it by 2. Your problem is that you have no lower bound.
int i = 2 * (27 + rand() % (106 - 27 + 1))
In general, to generate a random number in [a, b]
use:
int i = a + rand() % (b - a + 1)
To see why this works, try simple examples such as [2, 4]
, [3, 7]
etc.
answered Aug 1, 2010 at 18:58
2 Comments
IVlad
@Goutam -
rand()
generates a random number >= 0
. Taking it modulo b - a + 1
will put it in [0, b - a]
. Adding a
will put it in [a, b]
.lang-cpp