if...else 分支关键字 用法转自C语言if...else语句
1.if ... else语句在C编程语言的语法:
if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } else { /* statement(s) will execute if the boolean expression is false */ }
如果布尔表达式的计算结果为true,则if块中的代码将被执行,否则else块的代码将被执行。作为真正的C编程语言包括任何非零和非空值,如果它是零,那么它被假设为假值,否则为真值。
流程图:
#include int main () { /* local variable definition */ int a = 100; /* check the boolean condition */ if( a < 20 ) { /* if condition is true then print the following */ printf("a is less than 20\n" ); } else { /* if condition is false then print the following */ printf("a is not less than 20\n" ); } printf("value of a is : %d\n", a); return 0; }
上面的代码编译和执行时,它会产生以下结果:
a is not less than 20; value of a is : 100
一个if语句后面可以跟一个可选的...else if... else语句,这是非常有用的,可以测试各种条件,有几点要牢记。
>>>An if can have zero or one else and it must come after any else if's. //if后面可以跟人一多个else if但是只能有一个或者零个else
>>>An if can have zero to many else if's and they must come before the else.//不管什么时候else if都必须在else前
>>>Once an else if succeeds, none of the remaining else if's or else's will be tested.//一旦一个else if执行则接下来的else if和else都不执行
2.if(boolean_expression 1)//if ... else if... else语句在C编程语言的语法是:
{ /* 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 */ }
int main () { /* local variable definition */ int a = 100; /* check the boolean condition */ if( a == 10 ) { /* if condition is true then print the following */ printf("Value of a is 10\n" ); } else if( a == 20 ) { /* if else if condition is true */ printf("Value of a is 20\n" ); } else if( a == 30 ) { /* if else if condition is true */ printf("Value of a is 30\n" ); } else { /* if none of the conditions is true */ printf("None of the values is matching\n" ); } printf("Exact value of a is: %d\n", a ); return 0; }
None of the values is matching Exact value of a is: 1003.if中的易错点
- 有程序段:
- if(a=b)
- printf("%d",a);
- else
- printf("a=0");
- 在if语句中,if后面的条件(expression)必须用括号括起来且后面无分号。
- 执行部分如果如上所示仅为一条语句则可以不用{ }若为多条语句则必须用{ }阔气组成复合语句。注意执行语句后必须有;且在有{ }时 } 后面无分号;。
-
- if(a>b)
- {
- a++;
- b++;
- }
- else
- {
- a=0;
- b=10;
- }
题。例如:
if(表达式1)
if(表达式2)
语句1;
else
语句2;
其中的else究竟是与哪一个if配对呢?应该理解为:
if(表达式1)
if(表达式2)
语句1;
else
语句2;
还是应理解为:
if(表达式1)
if(表达式2)
语句1;
else
语句2;
为了避免这种二义性,C语言规定,else 总是与它前面最近的if配对,因此对上述例子应按前一种情况理解。
- #include <stdio.h>
- int main(void){
- int a,b;
- printf("please input A,B: ");
- scanf("%d%d",&a,&b);
- if(a!=b)
- if(a>b) printf("A>B\n");
- else printf("A<B\n");
- else printf("A=B\n");
- return 0;
- }
- #include <stdio.h>
- int main(void){
- int a,b;
- printf("please input A,B: ");
- scanf("%d%d",&a,&b);
- if(a==b) printf("A=B\n");
- else if(a>b) printf("A>B\n");
- else printf("A<B\n");
- return 0;
- }