条件语句

决策

``````int target = 10;
if (target == 10) {
printf("Target is equal to 10");
}
``````

`if`语句

`if`语句检查一个表达式是`真`还是`假`，并根据结果执行不同的代码。

``````int foo = 1;
int bar = 2;

if (foo < bar) {
printf("foo is smaller than bar.");
}

if (foo > bar) {
printf("foo is greater than bar.");
}
``````

``````int foo = 1;
int bar = 2;

if (foo < bar) {
printf("foo is smaller than bar.");
} else {
printf("foo is greater than bar.");
}
``````

``````int foo = 1;
int bar = 2;

if (foo < bar) {
printf("foo is smaller than bar.");
} else if (foo == bar) {
printf("foo is equal to bar.");
} else {
printf("foo is greater than bar.");
}
``````

``````int peanuts_eaten = 22;
int peanuts_in_jar = 100;
int max_peanut_limit = 50;

if (peanuts_in_jar > 80) {
if (peanuts_eaten < max_peanut_limit) {
printf("Take as many peanuts as you want!\n");
}
} else {
if (peanuts_eaten > peanuts_in_jar) {
printf("You can't have anymore peanuts!\n");
}
else {
printf("Alright, just one more peanut.\n");
}
}
``````

``````int foo = 1;
int bar = 2;
int moo = 3;

if (foo < bar && moo > bar) {
printf("foo is smaller than bar AND moo is larger than bar.");
}

if (foo < bar || moo > bar) {
printf("foo is smaller than bar OR moo is larger than bar.");
}
``````

NOT运算符`!`类似：

``````int target = 9;
if (target != 10) {
printf("Target is not equal to 10");
}
``````

Exercise

• 重要：不要忘记在要打印的字符串末尾添加一个换行符`\n`

Copyright © learn-c.org. Read our Terms of Use and Privacy Policy