Advertisement Jump to content
Sign in to follow this  
gnomer

exercise with rand()

This topic is 4914 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm having trouble with a little exercise in my book. It reads:
Quote:
For each of the following sets of integers, write a single statement that prints a number at random from the set: a) 2, 4, 6, 8, 10. b) 3, 5, 7, 9, 11. c) 6, 10, 14, 18, 22.
I can do it in multiple statements but I'm having trouble figuring out a single statement to do this. Probably simple but I'm not seeing it.

Share this post


Link to post
Share on other sites
Advertisement
a) std::cout << (std::rand()%5 + 1) * 2;
b) std::cout << ((std::rand()%5 + 1) * 2) + 1;
c) std::cout << (((std::rand()%5 + 1) * 2) + 1) * 2;

Share this post


Link to post
Share on other sites
Quote:
Original post by Mxz
a) std::cout << (std::rand()%4 + 1) * 2;
b) std::cout << ((std::rand()%4 + 1) * 2) + 1;
c) std::cout << (((std::rand()%4 + 1) * 2) + 1) * 2;


Shouldn't it be "rand()%5" and not "rand()%4"?

Share this post


Link to post
Share on other sites
Ok that makes sense. Again I was making it harder than it needed to be. Thanks very much for the help.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!