c语言if else代码程序,C语言if else语句

if语句可以跟着一个可选的else语句,当else执行时,布尔表达式为false。

语法

在C编程语言中的if … else语句的语法是:

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语言编程假定任何非零和非空值作为true,如果是零或null,则假定为false。

流程图:

a3ac51e90b68f6bd00071cc0210c4d40.png

例子:

#includeintmain(){/* local variable definition */inta=100;/* check the boolean condition */if(a<20){/* if condition is true then print the following */printf("a is less than 20 ");}else{/* if condition is false then print the following */printf("a is not less than 20 ");}printf("value of a is : %d ",a);return0;}

让我们编译和运行上面的程序,这将产生以下结果:

a is not less than 20; value of a is : 100

if…else if…else 语句

if语句可以跟着一个可选的else if … else语句,这是非常有用的使用单if语句测试if…else if 语句的各种条件。

当使用 if , else if , else语句有几点要记住:

一个 if 可以有零或一个else,它必须跟从else if之后(如果有else if)。

一个 if 可以有零到多个else if, 并且它们必须在else之前。

一旦一个else if成功,任何剩余else if或else将不会被测试。

语法

if…else if…else语句在C编程语言的语法是:

if(boolean_expression1){/* Executes when the boolean expression 1 is true */}elseif(boolean_expression2){/* Executes when the boolean expression 2 is true */}elseif(boolean_expression3){/* Executes when the boolean expression 3 is true */}else{/* executes when the none of the above condition is true */}

例子:

#includeintmain(){/* local variable definition */inta=100;/* check the boolean condition */if(a==10){/* if condition is true then print the following */printf("Value of a is 10 ");}elseif(a==20){/* if else if condition is true */printf("Value of a is 20 ");}elseif(a==30){/* if else if condition is true */printf("Value of a is 30 ");}else{/* if none of the conditions is true */printf("None of the values is matching ");}printf("Exact value of a is: %d ",a);return0;}

让我们编译和运行上面的程序,这将产生以下结果:

None of the values is matching Exact value of a is: 100

¥ 我要打赏 纠错/补充 收藏

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值