Jump to content
  • Advertisement
Sign in to follow this  
yurian

quick question

This topic is 4031 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

where does the number randomly selected by rand go? =) I mean, when the random number is selected, how do I use it? I read the tutorial on http://www.cplusplus.com/reference/clibrary/cstdlib/rand.html but I cant see where the randomly selected number is called. Maybe I have a weird problem? btw thanks to ppl who help me yesterday

Share this post


Link to post
Share on other sites
Advertisement
rand() is a function. Notice the two parenthesis after it. This means that it's a chunk of code somewhere else that can be called. When you call the function, it runs said chunk of code. Functions can also return a value. That is, once the chunk of code is done running, it gives the code that called it back a value. This value is placed where the function call is. rand() is calling the function rand. When it's called, it runs some code off somewhere that you don't need to see. When it's done, it returns the new random number.

Imagine that the '+' operator was a function (it is! But it looks odd). The function goes runs some code where you can't see that adds two numbers, and then returns the sum. When you evaluate '2 + 3', you get the sum, 5. The same thing happens with rand(), except that instead of summing something, it just chooses a random number. Just as you can assign '2 + 3' to a variable, you can assign rand().

int a = 2 + 3;
int b = rand();

It's the same principle. Just as 2 + 3 evaluates to 5, rand would evaluate to some random number. 5 becomes where '2 + 3' is, and is then given to the variable a. Similarly, the random number becomes where the function call is, which is then given to the variable b.

You can, naturally, do things to the value returned by rand(). Such as add three, take the modulus of it and 10, or divide by 2.3.

int c = rand() % 10 + 1;

And now we are where Talroth is.

Hope that helps.

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!