Random numbers are useful in many situations, not just games, but also in serious applications such as simulations, educational software and others. The statement R= Rnd() assigns a value to R such that 0 <= R<1. The table below shows the transformation of a random number to a random value from 1 to 6:
Instead of doing this step-by-step as shown above the following statement
can be used: A general rule is to multiply by the number of values in the range and
then add the lowest value in the range.
Random Points on the FormTo get a random point on the form use the following statements: Weighted ValuesIn the examples above, each value in the range has an equal chance of being selected. This would be true if we were using random numbers to roll dice, or flip a coin. In other application, we prefer to have one value appear more often than other values. In a bank simulation, we may say that 80% of the customers have just one transaction, 15% have 2 transactions, and 5% have 3 transactions. The easiest way to handle problems of this type is to generate a random value from 1 to 100 and then assign a range of value based on the percentage: 1..80 = 1 transaction Exercise: (not a lab assignment) Create a program with one button. When the button is clicked generate random x and y values then draw a square at that point. Test. Modify so that 80% of the boxes are blue, 15% red, and 5% yellow. |
|---|