Functions - PowerPoint PPT Presentation

1 / 8
About This Presentation
Title:

Functions

Description:

If you run a program containing the rand function you will notice the same ... Please read the comments in the program examples carefully. ... – PowerPoint PPT presentation

Number of Views:11
Avg rating:3.0/5.0
Slides: 9
Provided by: dilshad7
Learn more at: https://cs.nyu.edu
Category:

less

Transcript and Presenter's Notes

Title: Functions


1
Functions
  • Dilshad M. Shahid
  • New York University
  • _at_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
    ltstdlib.hgt header file. rand itself is in
    ltstdlib.hgt 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 ltstdlib.hgt

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.
Write a Comment
User Comments (0)
About PowerShow.com