1 / 8

Functions

Functions. Dilshad M. Shahid New York University @1999. Today. Random number generation. Random Number Generation. There is a function called rand which will generate random numbers rand returns an integer value so you could call it in this way: i = rand(); /* i is of type int */

dory
Download Presentation

Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Functions Dilshad M. Shahid New York University @1999

  2. Today • Random number generation

  3. Random Number Generation • There is a function called rand which will generate random numbers • rand returns an integer value so you could call it in this way: i = rand(); /* i is of type int */ • rand function generates an integer between 0 and RAND_MAX • RAND_MAX is a symbolic constant defined in <stdlib.h> header file. rand itself is in <stdlib.h> which you will have to include in your program if you want to use the rand function

  4. Random Number Generation • Since rand() produces such large numbers we often use the following to scale it down, e.g. : rand() % 6 • This would produce (in this case) numbers between 0 and 5 (all the possible remainders when any number is divided by 6) • Similarly, rand() % 4 would return numbers between 0 and 3

  5. Random Number Generation • If you run a program containing the rand function you will notice the same output each time you run it • How come, if rand is generating random numbers? • The truth is rand actually generates pseudo-random numbers

  6. Random Number Generation • To actually produce a different sequence of numbers, it has to be conditioned • This is called randomizing and we use the standard library function srand • srand takes an unsigned integer argument and seeds the rand function

  7. Random Number Generation • An unsigned int is stored in at least 2 bytes of memory (like a regular int) but can only have a positive value between 0 and 65535 • An int can have both positive and negative values between -32767 and +32767 • srand is also in <stdlib.h>

  8. Random Number Generation • Check out the 2 examples with rand and srand on the web page. • Please read the comments in the program examples carefully.

More Related