views:

59

answers:

1

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;
}
+6  A: 

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.

IVlad
thanks, this worked fine
@user69514: You should accept the answer if it works!
jigfox