Jump to content
• What is your GameDev Story?

• Advertisement

Public Group

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

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

Share on other sites
Quote:
 Original post by Mxza) 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

Share on other sites
Yea, fixed it just before you posted. [smile]

Share this 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

Share on other sites

• Advertisement
• Advertisement
• What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

(You must login to your GameDev.net account.)

• Popular Now

• 27
• 16
• 10
• 10
• 11
• Advertisement
• Forum Statistics

• Total Topics
634101
• Total Posts
3015529
×

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!