Cprogramming 简明教程

C - The If Statement

条件执行指令是计算机程序的基本要求。C 中的 if 语句是主要的条件语句。C 允许使用可选的 else 关键字来指定如果 if 条件为 false 则要执行的语句。

Conditional execution of instructions is the basic requirement of a computer program. The if statement in C is the primary conditional statement. C allows an optional else keyword to specify the statements to be executed if the if condition is false.

C - if Statement

if 语句是 C 编程中很基础的 decision control statement 。具体执行块中一个或多个语句将根据 if 语句中的布尔条件为真或假而决定。

The if statement is a fundamental decision control statement in C programming. One or more statements in a block will get executed depending on whether the Boolean condition in the if statement is true or false.

Syntax of if Statement

if 语句的编写符合以下语法:

The if statement is written with the following syntax −

if(boolean_expression) {
   /* statement(s) will execute if the boolean expression is true */
}

How if Statement Works?

C 使用一对花括号形成代码块。如果布尔表达式求值为真,则 if 语句中的代码块将被执行。

C uses a pair of curly brackets to form a code block. If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed.

如果布尔表达式求值为假,则 if 语句结尾后(即闭括号后)的第一组代码将被执行。

If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed.

C 编程语言将所有非零且非空值视为真。如果值要么为零要么为空,则被视为假值。

C programming treats any non-zero and non-null values as true. And if the values are either zero or null, then they are treated as false values.

Flowchart of if Statement

if 语句的行为由以下流程图表示:

The behaviour of the if statement is expressed by the following flowchart −

if statement

Flowchart Explained

当程序控制遇到 if 语句时,此条件将得到评估。

When the program control comes across the if statement, the condition is evaluated.

如果条件为真,则 if 块中的语句将被执行。

If the condition is true, the statements inside the if block are executed.

如果条件为假,则程序流程将绕过条件块。

If the condition is false, the program flow bypasses the conditional block.

if 块后的语句将被执行,以继续程序流程。

Statements after the if block are executed to continue the program flow.

Example of if Statement in C

该示例说明了 if 语句的最简单用例。它确定并告知用户某个变量的值是否小于 20。

This example demonstrates the simplest use-case of if statement. It determines and tells the user if the value of a variable is less than 20.

#include <stdio.h>

int main (){

   /* local variable declaration */
   int a;

   // run the program for different values of "a"
   // Assign 12 first and 40 afterwards

   a = 12;  //change to 40 and run again
   printf("Value of a is : %d\n", a);

   // check the boolean condition using if statement

   if(a < 20){
      //if the condition is true, then print the following
      printf("a is less than 20\n" );
   }
   return 0;
}

运行以上程序并检查其输出:

Run the above program and check its ouput −

Value of a is : 12
a is less than 20

现在分配大于 20 的数字。 if 条件未被执行。

Now assign a number greater than 20. The if condition is not executed.

Value of a is: 40

if Statement with Logical Operations

你可以在 if 语句中括号内的 &&|| 运算符中放置复合布尔表达式。

You can put a compound boolean expression with the use of && or || operators in the parenthesis in the if statement.

Example

在以下示例中,比较了三个 variables “a”、“b”和“c”。当“a”大于“b”和“c”时, if 块将被执行。

In the following example, three variables "a", "b" and "c" are compared. The if block will be executed when "a" is greater than both "b" and "c".

#include <stdio.h>

int main () {

   /* local variable declaration */
   int a, b, c;

   /*use different values for a, b and c as
   10, 5, 7
   10, 20, 15
   */

   // change to 10,20,15 respectively next time
   a = 10; b = 5; c = 7;

   if (a>=b && a>=c){
      printf ("a is greater than b and c \n");
   }
   printf("a: %d b:%d c:%d", a, b, c);

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

//when values for a, b and c are 10 5 7
a is greater than b and c
a: 10 b:5 c:7

//when values for a, b and c are 10 20 15
a: 10 b:20 c:15

注意,紧跟在条件块后面的语句在该块执行之后被执行。如果条件为假,则程序直接跳转到该块后的语句。

Note that the statement following the conditional block is executed after the block is executed. If the condition is false, the program jumps directly to the statement after the block.

Multiple if Statements

如果你有多个条件要检查,则你可以多次使用 if 语句。

If you have multiple conditions to check, you can use the if statement multiple times.

Example

在此示例中,净应付金额是通过对账单金额应用折扣来计算的。

In this example, the net payable amount is calculated by applying discount on the bill amount.

如果金额在 1000 至 5000 之间,则适用 5% 的折扣,如果金额高于 5000,则适用 10% 的折扣。低于 1000 的采购不适用折扣。

The discount applicable is 5 percent if the amount is between 1000 to 5000, and 10 percent if the amount is above 5000. No discount is applicable for purchases below 1000.

#include <stdio.h>

int main () {

   // local variable declaration
   int amount;
   float discount, net;

   /*Run the program for different values
   of amount – 500, 2250 and 5200. Blocks in
   respective conditions will be executed*/

   // change to 2250 and 5200 and run again
   amount = 500;

   if (amount < 1000){
      discount=0;
   }
   if (amount >= 1000 && amount<5000){
      discount=5;
   }
   if (amount >= 5000){
      discount=10;
   }
   net = amount - amount*discount/100;
   printf("Amount: %d Discount: %f Net payable: %f", amount, discount, net);

   return 0;
}
//when the bill amount is 500
Amount: 500 Discount: 0.000000 Net payable: 500.000000

//when the bill amount is 2250
Amount: 2250 Discount: 5.000000 Net payable: 2137.500000

//when the bill amount is 5200
Amount: 5200 Discount: 10.000000 Net payable: 4680.000000

Checking Multiple Conditions With if Statement

你还可以使用一个 if 语句中的逻辑运算符检查多个条件。

You can also check multiple conditions using the logical operators in a single if statement.

Example

在这个程序中,当“phy”和“maths”成绩的平均分大于等于 50 时,学生才被声明为 passed 。此外,学生在两个科目中都应该获得超过 35 分。否则,学生将被声明为 failed

In this program, a student is declared as passed only if the average of "phy" and "maths" marks is greater than equal to 50. Also, the student should have secured more than 35 marks in both the subjects. Otherwise, the student is declared as failed.

#include <stdio.h>

int main (){
   /* local variable declaration */
   int phy, maths;
   float avg;

   /*use different values of phy and maths
   to check conditional execution*/

   //change to 40, 40 and 80, 40
   phy = 50; maths = 50;
   avg = (float)(phy + maths)/2;
   printf("Phy: %d Maths: %d Avg: %f\n", phy, maths, avg);

   if (avg >= 50 && (maths >= 35 && phy >= 35)){
      printf("Result: Pass");
   }

   if (avg<50) {
      printf("Result: Fail\n");
   }
   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

//when marks in Phy and Maths - 50 50
Phy: 50 Maths: 50 Avg: 50.000000
Result: Pass

//when marks in Phy and Maths - 40 40
Phy: 40 Maths: 40 Avg: 40.000000
Result: Fail

//when marks in Phy and Maths - 80 40
Phy: 80 Maths: 40 Avg: 60.000000
Result: Pass