Nested decisions
หน้านี้ต้องใช้เบราว์เซอร์ล่าสุด (รองรับ SharedArrayBuffer) กรุณาอัปเดต Chrome, Edge, Firefox หรือ Safari เป็นเวอร์ชันล่าสุด
English
One speed, three outcomes
- A speed camera: 120 or more loses the licence, 100 or more is a fine, and anything lower is ok.
- One
IFhas two paths. The second decision goes inside theELSE, as its ownIF. - Each
IFhas its ownENDIF. Indent the inner one so you can see whichELSEit belongs to.
English
DECLARE Speed : INTEGER
Speed ← 105
IF Speed >= 120
THEN
OUTPUT "licence taken"
ELSE
IF Speed >= 100
THEN
OUTPUT "fine"
ELSE
OUTPUT "ok"
ENDIF
ENDIF
Speed |
Speed >= 120 |
Speed >= 100 |
Output |
|---|---|---|---|
| 130 | TRUE |
not tested | licence taken |
| 105 | FALSE |
TRUE |
fine |
| 100 | FALSE |
TRUE |
fine |
| 90 | FALSE |
FALSE |
ok |
- Test the highest boundary first. If
Speed >= 100came first, 130 would get only a fine.
English
Count the marks that count
- A validation tally walks the array and adds 1 only when the value is in range.
- The range test is the
ANDfrom the previous lesson, inside the loop.
English
DECLARE Temp : ARRAY[1:5] OF INTEGER
DECLARE Day, Count : INTEGER
Temp[1] ← 21
Temp[2] ← 99
Temp[3] ← -5
Temp[4] ← 18
Temp[5] ← -60
Count ← 0
FOR Day ← 1 TO 5
IF Temp[Day] >= -50 AND Temp[Day] <= 50
THEN
Count ← Count + 1
ELSE
OUTPUT "Day ", Day, " reading rejected"
ENDIF
NEXT Day
OUTPUT Count, " readings accepted"
- A thermometer reading outside -50 to 50 is a fault. The
ELSEreports which day was rejected.
English
Watch out
- The inner
IFstarts on the line afterELSE. It is not written on theELSEline. - Close the inner
ENDIFbefore the outer one. The lastENDIFbelongs to the firstIF.
English
Common mistakes
- An
ENDIFin the wrong place closes the outer test and leaves the inner one open. - A speed of exactly 100 is a fine, and exactly 120 loses the licence. The tests use
>=, so check the boundary values.
English
Now you try
- The first two tasks are a nested grade with boundaries 80 and 50. The third counts the marks from 0 to 100 with
AND. - Press Check answer to test it.
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Read an INTEGER Mark. Output Distinction for 80 or more, otherwise Pass for 50 or more, otherwise Fail. Nest the second IF ใต้ ELSE.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Same three outcomes as the previous task. A mark below 50 must reach the inner ELSE; the check also tries marks that must not.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
The array Mark มีไว้ 80, -1, 100, 40. Count how many values are from 0 ไป 100 inclusive and output the count (it is 3).
คลิก Run เพื่อดูผลลัพธ์ที่นี่