C语言第二章Conditionals and Loops

Conditionals

Conditionals are used to perform different computations or actions depending on whether a condition evaluates to true or false.
The if statement is called a conditional control structure because it executes(执行) statements when an expression is true. For this reason, the if is also known as a decision structure. It takes the form:

if (expression)
  statements

The expression evaluates to either true or false, and statements can be a single statement or a code block enclosed by curly braces { }.

Relational Operators(关系运算符)

Conditional Expressions(条件表达式)

Another way to form an if-else statement is by using the ?: operator in a conditional expression. The ?: operator can have only one statement associated with the if and the else.

Nested if Statements(嵌套 if 语句)

An if statement can include another if statement to form a nested statement. Nesting an if allows a decision to be based on further requirements.
Consider the following statement:

#include <stdio.h>

int main() {
   
    int profit = 1400;
    int clients = 18;
    int bonus;
    
    if (profit > 1000)
        if (clients > 15)
            bonus = 100;
        else
            bonus = 25;
    
    printf("%d", bonus);
}

suggest explicit braces to avoid ambiguous ‘else’
Appropriately indenting nested statements will help clarify the meaning to a reader. However, be sure to understand that an else clause is associated with the closest if unless curly braces { } are used to change the association.

The if-else if Statement

When a decision among three or more actions is needed, the if-else if statement can be used.
There can be multiple else if clauses and the last else clause is optional.
Carefully consider the logic involved when developing an if-else if statement. Program flow branches to the statements associated with the first true expression and none of the remaining expressions will be tested.
Although ind

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值