Hands On

Functions and Random numbers

Goal

To gain experience using functions and learn how to generate random numbers.

We will write a game program that allows a person to guess a random number.

Guess My Number Game

Enter a guess between 1 and 100 : 4
Too low!
Enter a guess between 1 and 100 : 6
Too low!
Enter a guess between 1 and 100 : 50
Too high!
Enter a guess between 1 and 100 : 25
Too low!
Enter a guess between 1 and 100 : 35
Too high!
Enter a guess between 1 and 100 : 30
Too low!
Enter a guess between 1 and 100 : 32
Too low!
Enter a guess between 1 and 100 : 34
Too high!
Enter a guess between 1 and 100 : 33

Correct! You got it in 9 guesses!

Step 1

Review page on generating random numbers.

Questions:

1. How do you generate a number between 1 and 100 (inclusive)?

2. How do you generate a double number between n and m where 0 <= n < m?

Write and test functions:

void initRandom();
int getRandomInt(int min,int max);
double getRandom();

Step 2

Using the functions above write the number guessing game shown in the introduction.

Step 3

Write a program that generates 100 numbers between 1 and 50. What is the average of these numbers? Can you compute the median of the numbers?

Edit | Attach | Watch | Print version | History: r2 < r1 | Backlinks | Raw View | Raw edit | More topic actions
Topic revision: r2 - 2017-02-21 - JimSkon
 
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2019 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback