由一个条件句去判断 bool 值,若是true
就执行 statement,false
就跳过。
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
跟上面很像,就差在else,在 bool值为false
时会执行 statement2。
if(boolean_expression)
{
/* statement1(s) will execute if the boolean expression is true */
}
else
{
/* statement2(s) will execute if the boolean expression is false */
}
ex.
int main() {
int a = 100;
if (a < 20) {
NSLog(@"a 小於 20");
} else {
NSLog(@"a 大於 20");
}
NSLog(@"value of a is : %d",a);
return 0;
}
结果:
2021-09-15 17:39:42.936729+0800 TestOC[81516:975631] a 大於 20
2021-09-15 17:39:42.937428+0800 TestOC[81516:975631] value of a is : 100
可以用来测试各种条件。
当使用 if , else if , else 语句时,有几点要牢记:
if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
/* Executes when the boolean expression 3 is true */
}
else
{
/* executes when the none of the above condition is true */
}
ex.
#import <Foundation/Foundation.h>
int main() {
int a = 20;
if (a == 10) {
NSLog(@"a 等於 10");
} else if (a == 20){
NSLog(@"a 等於 20");
} else if (a == 30){
NSLog(@"a 等於 30");
} else {
NSLog(@"value of a is : %d",a);
}
return 0;
}
与 if 语句不同的地方在於,if 主要判断条件的对错(bool值),只会有两种情况(true
, false
) ; 而 switch 则可以有许多情况,可用於多种可能。
switch(expression){
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
ex.
#import <Foundation/Foundation.h>
int main() {
char grade = 'B';
switch (grade) {
case 'A' :
NSLog(@"Excellent!");
break;
case 'B' :
case 'C' :
NSLog(@"Well done");
break;
case 'D' :
NSLog(@"You passed");
break;
case 'F' :
NSLog(@"Better try again");
break;
default :
NSLog(@"Invalid grade");
}
NSLog(@"Your grade is %c", grade);
return 0;
}
结果:
2021-09-15 18:09:25.397015+0800 TestOC[81888:995326] Well done
2021-09-15 18:09:25.397875+0800 TestOC[81888:995326] Your grade is B
可以用来代替 if...else 语句
Bool ? Exp2 : Exp3;
如果 Bool 为true
,会跑到 Exp2。反之,为false
,会跑到 Exp3。
Object 本身自带 [[Get]] 机制能帮我们找到符合 property name (或说 k...
在手机装置中, Flexbox 弹性盒子是一个重点样式 倘若你不懂,就只能躺着被打 orz Rea...
MQTT 通讯协定 最後一天就是要把大家领进门, 来把上回的智慧装置串接到 Home Assista...
一个人厉害永远比不上一群人厉害 某次跟同事闲聊时谈到这件事 我们一致认同在一个团队里 大家都是互相...
在前一章我们学到chart是如何运作的,他能够将values内的值带入deployment.yaml...