Random Values
| English | Chinese | Pinyin |
|---|---|---|
| unpredictable | 不可预测 | bù kě yù cè |
| random | 随机 | suí jī |
| range | 范围 | fàn wéi |
| variability | 可变性 | kě biàn xìng |
| outputs | 输出 | shū chū |
Unpredictable on purpose
- Some programs need to be unpredictable — games, tests, simulations.
- A program can generate a random 随机 value within a specified range 范围.
RANDOM(1, 6)might return any whole number from 1 to 6, each with an equal chance.- It is like a dice built into the program.
RANDOM(1, 6) returns:
It picks a random value within the given range.
Variability
- Randomness introduces variability 可变性 into a program's behaviour.
- Two runs of the same program can then behave differently.
- That is exactly what makes a game feel fresh each time.
- Nothing in the code changed — only the random value did.
Same every run, or varies?
A random value makes output vary between runs; a fixed calculation gives the same output every time.
Randomness introduces ______ so two runs can behave differently.
The same code can give different results each run.
roll ← RANDOM(1, 6) does what?
The generated value is stored in the variable.
Store and use it
- You usually store a random value in a variable for later logic:
- $\text{roll} \leftarrow \text{RANDOM}(1, 6)$.
- Now
rollholds one dice value the rest of the program can use. - Random values let a program model unpredictable 不可预测 events, like a coin flip.
Getting 4, then 1, then 6 from three runs of a dice program is expected, not a bug.
The random value differs each run, so the output differs.
A coin-flip program uses RANDOM(1, 2). The two possible outputs are:
1 maps to heads, 2 to tails.
Random values let a program model unpredictable events like a dice roll.
This makes programs feel more like the real world.
Different outputs each run
- Because of randomness, repeated runs can produce different outputs 输出.
- Running a dice program three times might give 4, then 1, then 6.
Coin flip. A program picks RANDOM(1, 2), treating 1 as "heads" and 2 as "tails". One run stores 1 → "heads"; the next stores 2 → "tails". Nothing in the code changed — only the random value differs, so the output differs. This is expected, not a bug.
A random value is picked within a range (RANDOM(1, 6)), adding variability so two runs can differ. Store it in a variable to use it, and it lets a program model unpredictable events. Different outputs across runs are expected, not a bug.