开发者

Create a random even number between range

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开发者_如何学Go 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;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜