supp-random

supp-random - CSC 1111 Introduction to Computing using C+...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon
1 CSC 1111 Introduction to Computing using C++ Random Numbers Generation
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 Random Number Generation rand() is a function that returns a pseudo-random number between 0 and RAND_MAX RAND_MAX is a predefined symbolic constant and is compiler dependent (usually 32767) Each call to rand() yields a different number x = rand(); x can be any integer between 0 and RAND_MAX Need to include <cstdlib> to use the random functions
Background image of page 2
3 // A program to print 20 random numbers #include <iostream> using namespace std; #include <cstdlib> // need this header for using rand() int main() { cout << "RAND_MAX = " << RAND_MAX << endl; for ( int i = 0 ; i < 20 ; i++) { cout << rand() << " " ; if (i % 5 == 4 ) // 5 integers per line cout << endl; } return 0 ; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 RAND_MAX = 32767 16838 5758 10113 17515 31051 5627 23010 7419 16212 4086 2749 12767 9084 12060 32225 17543 25089 21183 25137 25566
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
4 Scaling and Shifting Scaling rand() % range Yields a random number in [ 0, range – 1] e.g. : x = rand % 100; // x in [0, 99] Scaling and Shifting N + rand() % range Yields a random number in [N, N + range – 1] e.g. : x = -50 + rand() % 100 // x in [-50, 49] How to yield a random number in [A, B]?
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 12/28/2010 for the course CSC CSC1110 taught by Professor Cjyuan during the Fall '06 term at CUHK.

Page1 / 14

supp-random - CSC 1111 Introduction to Computing using C+...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online