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

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

View Full Document Right Arrow Icon
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.
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 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.
Background image of page 2
3 Seeding Your Randomness r The srand(int) function starts reading the list at the seed position specified by the passed int. srand(10);
Background image of page 3

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

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

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 Right Arrow Icon
Ask a homework question - tutors are online