Public Group

# 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.

## 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 on other sites
iSecret = rand() % 10 + 1;

The random number generated by rand() is stored in iSecret.

##### Share on other sites
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.

1. 1
2. 2
3. 3
Rutin
22
4. 4
JoeJ
16
5. 5

• 14
• 29
• 13
• 11
• 11
• ### Forum Statistics

• Total Topics
631774
• Total Posts
3002291
×