If 和 Else If 之间的区别?

2022-09-01 01:17:41

我想知道为什么你会使用一个语句,而不是多个语句?例如,这样做有什么区别:else ifif

if(i == 0) ...
else if(i == 1) ...
else if(i == 2) ...

还有这个:

if(i == 0) ...
if(i == 1) ...
if(i == 2) ...

他们似乎在做同样的事情。


答案 1
if(i == 0) ... //if i = 0 this will work and skip the following else-if statements
else if(i == 1) ...//if i not equal to 0 and if i = 1 this will work and skip the following else-if statement
else if(i == 2) ...// if i not equal to 0 or 1 and if i = 2 the statement will execute


if(i == 0) ...//if i = 0 this will work and check the following conditions also
if(i == 1) ...//regardless of the i == 0 check, this if condition is checked
if(i == 2) ...//regardless of the i == 0 and i == 1 check, this if condition is checked

答案 2

不同之处在于,如果第一个是真的,那么所有其他的都不会被执行,即使它们确实计算为true。但是,如果它们是单个 s,则如果它们评估为 true,则所有 s 都将被执行。ifelse ififif


推荐