此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
C 里的真与假
- 默认情况下,C 没有单独的真/假类型。它用数字:
0表示假,任何其他数字表示真。 - 像
5 > 3这样的判断会得到1(真)。5 < 3会得到0(假)。 - (如果你
#include <stdbool.h>,就能写bool、true、false—— 但普通的int在哪里都能用。)
比较与组合
- 用
==(等于)、!=(不等于)、<、>、<=、>=来比较值。 - 小心:
==判断是否相等;单个=是赋值。两者不一样! - 用
&&(与)、||(或)、!(非)来组合判断。a && b只有在两者都为真时才为真。
if / else if / else
if (test) { ... }仅在测试条件为真时才执行该代码块。- 加
else if (...)检查另一个判断,加else表示“以上都不是”。 - 只有第一个满足的分支会运行。
English
#include <stdio.h>
int main(void) {
int score = 72;
if (score >= 90) {
printf("A\n");
} else if (score >= 60) {
printf("Pass\n"); // this one runs
} else {
printf("Fail\n");
}
return 0;
}
switch:在多个值中选择
switch根据一个值(int或char)来选择分支。- 每个
case都以break;结尾,因此不会落入下一个分支。default:捕获其余所有情况。 - 当你要把同一个变量和许多固定的值比较时,
switch很清爽。
常见错误
- 比较用
==;=是赋值(而if (x = 5)永远为真)。 - 忘记
break;会导致某个情况穿透到下一个情况中。仅在有意为之时才省略,例如当case 10:共享case 9:的代码时。
现在轮到你
- 用比较和
&&/||来构建你的判断。记住0是假,其他都是真。 - 在
switch任务里,先把 score 除以 10,再对结果做 switch。 - 不要自己写
main—— 检查器会提供。
探索
if / else if / else
Conditions test top-down; the first true block runs.
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Complete int sign(int n) so it returns -1 when n is negative, 0 when n is zero, and 1 when n is positive. Do 不 write a main.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Complete int in_range(int n, int lo, int hi) so it returns 1 when n is between lo and hi (inclusive), and 0 otherwise. Use &&. Do 不 write a main.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Complete char grade_letter(int score) using a switch on score / 10. Return 'A' for 90–100, 'B' for the 80s, 'C' for the 70s, 'D' for the 60s, and 'F' below 60. Do 不 write a main.
点击“运行”查看此处输出。