Step 5
Making decisions
Compare values, and choose what to do with if, else if and else.
true or false
A comparison asks a question and gives back a bool: true or false.
| Comparison | Means |
|---|---|
a < b, a > b | less than, greater than |
a <= b, a >= b | less than or equal, greater than or equal |
a == b | equal (two =, because one = stores a value) |
a != b | not equal |
Combine them with && (and: both must be true), || (or: at least one must be) and ! (not):
bool ok = angle >= 0 && angle <= 3.14;
Write each comparison out in full. 0 <= angle <= 3.14 compiles, but it doesn't mean what it looks like: C++ works out 0 <= angle first, gets true or false (1 or 0), and compares that with 3.14.
std::cout prints a bool as 1 or 0. Send it std::boolalpha first to see true and false.
if, else if, else
if runs its block only when the condition in parentheses is true. else if tries another condition when the ones above were false, and else catches everything left over:
std::string describe(double speed) {
if (speed > 1.0) {
return "fast";
} else if (speed > 0) {
return "moving";
} else {
return "stopped";
}
}
C++ checks the conditions from the top and runs only the first block whose condition is true. That's why the else if doesn't need to say speed <= 1.0: it's only reached when speed > 1.0 was false. return ends the function straight away, so nothing after it runs.
Your task
- Write
choose_action(distance). The gripper isdistancemetres from a ball. Return"grab"when it's closer than 0.05 m,"approach"when it's closer than 0.5 m, and"wait"otherwise. - Write
in_limits(angle, low, high). Returntruewhenangleis betweenlowandhigh, ends included, andfalseotherwise.
The grader tries values right on the boundaries, so think about < versus <=.