Lec13 - Lecture 13 Random Numbers PIC 10A Todd Wittman Sec...

This preview shows pages 1–4. Sign up to view the full content.

1 Lecture 13: Random Numbers PIC 10A Todd Wittman Sec 3.11 : Random Numbers r The rand() function creates a random integer between 0 and RAND_MAX, a constant about 32,000. r To generate a random integer in the range [a,b] use a + rand()%(b-a+1); r Ex Simulate the roll of a die. r Ex Generate a random even integer between 2 and 10.

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

View Full Document
2 int i = 1; while (i <= 20) { int rand_num = rand(); cout << rand_num << "\n"; i++; } Gives the same output every time we run it! 4 runs of the program Seeding Your Randomness r The problem is that the rand() function doesn’t really generate a random number. r It just reads a number from a really long built-in list of integers. r So it always reads the same list every time we restart the program. r To make it look more random, we should start reading the list from a different spot. r This is called seeding the random number generator.
3 Seeding Your Randomness r The srand(int) function starts reading the list at the seed position specified by the passed int. srand(10);

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 04/27/2010 for the course PIC 157-050-21 taught by Professor Wittman during the Fall '10 term at UCLA.

Page1 / 6

Lec13 - Lecture 13 Random Numbers PIC 10A Todd Wittman Sec...

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

View Full Document
Ask a homework question - tutors are online