quick question

Started by
1 comment, last by Ezbez 16 years, 9 months ago
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
Advertisement
iSecret = rand() % 10 + 1;

The random number generated by rand() is stored in iSecret.
Old Username: Talroth
If your signature on a web forum takes up more space than your average post, then you are doing things wrong.
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.

This topic is closed to new replies.

Advertisement