Question:

Who can explain the rand() function in C

by  |  earlier

0 LIKES UnLike

Please explain in a little depth

I have searched for this function at heaps of places and everyone just goes popping alien stuff about srand and seeding and randmax as if i knew it from birth

Please understand I don't know anything about any related stuff too !

And i promise to award 10 pts to the deserving one ....

 Tags:

   Report

3 ANSWERS


  1. Okay, here goes.

    Each time you call rand(), it will give you a number.  They'll look like random numbers, but really it's just the result of a complicated mathematical formula.

    The problem with this is if you run your program and it gives you 5, 421, 35, 1853 then the next time you run your program, it will give you the exact same sequence of numbers.  That's annoying.

    So what you do is called "seeding the random number generator".  That's basically just telling it "okay, start from here".  If each time you tell it to start from a different number, then the sequence will be different each time you run your program.

    So...what's a number that's going to be unique each time you run your program?  There are various possibilities, but the most obvious is the date+time.  Obviously, next time you run your program, it will be a different time of day, or a different day, or both.

    So if you use srand(time()) to seed the random number generator with the current time, you'll get a different sequence of "random" numbers each time you run your program.


  2. Here's a video that explains rand and how to use it:

    http://xoax.net/comp/cpp/console/Lesson2...

    Let me know you have more questions on it:

    http://xoax.net/forum/

  3. If you don't know anything about C, why are you asking?  You have to understand some fundamentals in order to understand the answer.

    http://www.opengroup.org/onlinepubs/0096...

Question Stats

Latest activity: earlier.
This question has 3 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions