Selection in C
C Programming Lesson 3 2:29 English narration · English + 中文 subtitles burned in
Chapters
Transcript
C does not have a true-or-false type the way the other languages here do.
C 没有别的语言那样的真假类型。
Instead it has a rule: zero is false, and everything else — one, forty-two, even minus three — is true.
它有的是一条规则: 0 是假,其他一切——1、42,甚至 -3——都是真。
And when you write a comparison, C hands back one or zero as an ordinary number.
而当你写一个比较时,C 交还的是 1 或 0 这样一个普通的数字。
That is not a curiosity; it means a comparison can be returned from a function, stored in an int, or added up, and you will use that in this lesson's second task.
这不是什么冷知识;它意味着一个比较可以被函数返回、存进 int,甚至被累加, 而这一课的第二题正要用到它。
Here is the sign function from this lesson. Two tests and a fallback.
这是这一课里的 sign 函数:两个判断,加一个兜底。
If the number is negative, return minus one and leave immediately.
如果这个数是负数,返回 -1 并立刻离开。
If it is positive, return one.
如果是正数,返回 1。
And if neither test fired, the last line runs and returns zero — which is exactly the case where the number IS zero.
如果两个判断都没触发,就执行最后一行,返回 0—— 而这正好就是这个数等于 0 的情况。
Because return leaves the function at once, the later lines only run when the earlier tests have failed.
因为 return 会立刻离开函数,后面的行只有在前面的判断都失败时才会执行。
When you are testing one value against many possibilities, a switch says it more clearly than a chain of ifs.
当你要拿一个值和很多种可能作比较时,switch 比一串 if 更清楚。
The value is worked out once at the top, and each case names one possible result.
这个值在开头只求一次,每个 case 给出一种可能的结果。
Stacked cases share an answer — ten and nine both give A.
连写的 case 共用同一个答案——10 和 9 都得到 A。
And the trap: without a return or a break, control falls through into the next case and keeps going, which is occasionally useful and usually a bug.
而陷阱是:如果没有 return 或 break,控制流会掉进下一个 case 继续往下走, 这偶尔有用,但通常是个 bug。
Now the lesson's second task: does a number lie between two others?
现在做课程里的第二道题:一个数是否落在另外两个数之间?
The obvious version writes the test, then return one or return zero in two branches.
最直白的写法是写出判断,然后在两个分支里分别 return 1 和 return 0。
It is correct.
这样是对的。
But remember what a comparison hands back: the whole test is already one or zero, so you can return the test itself, on one line.
但想想比较返回的是什么: 整个判断本身已经是 1 或 0,所以你可以直接把这个判断返回出去,只要一行。
Shorter, and it says exactly what it means.
更短,而且它表达的正是它的意思。
Four things to take with you.
带走四点。
One: zero is false and everything else is true.
第一:0 是假,其他一切都是真。
Two: a comparison gives one or zero, so you can return it directly.
第二:比较的结果是 1 或 0,所以可以直接把它返回。
Three: ifs and else-ifs are checked in order, and return leaves at once.
第三:if 和 else if 按顺序检查,而 return 会立刻离开。
Four: every switch case needs a return or a break, or it falls through.
第四:每个 switch 分支都需要 return 或 break,否则会掉到下一个分支。
Now do the three tasks; the last one is a switch on the score divided by ten.
现在去做那三道题;最后一题要对分数除以 10 的结果做 switch。