0

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
2
  • Is this some kind of a homework? Commented Aug 1, 2010 at 18:55
  • Why do you want to do this in a single statement? Is this homework? Commented Aug 1, 2010 at 18:56

1 Answer 1

10

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

Can you please explain the logic?
@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].

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.