Cprogramming 简明教程

C - The if-else Statement

if-else 语句是 C 中最常用的 decision-making statements 之一。 if-else 语句在条件未满足时提供了备选路径。

The if-else statement is one of the frequently used decision-making statements in C. The if-else statement offers an alternative path when the condition isn’t met.

if 语句中的布尔表达式变为假时, else 关键词帮助你提供一个备选行动方针。使用 else 关键词是可选的;是否使用它取决于你。

The else keyword helps you to provide an alternative course of action to be taken when the Boolean expression in the if statement turns out to be false. The use of else keyword is optional; it’s up to you whether you want to use it or not.

Syntax of if-else Statement

以下是 if-else 子句的语法 −

Here is the syntax of if-else clause −

if (Boolean expr){
   Expression;
   . . .
}
else{
   Expression;
   . . .
}

C compiler 评估条件,如果该条件为 true,将执行 if statement 之后的一个语句或一个语句块。

The C compiler evaluates the condition, and executes a statement or a block of statements following the if statement if it is true.

如果编程逻辑需要计算机在条件为 false 时执行一些其他指令,则这些指令会被作为 else 子句的一部分放置。

If the programming logic needs the computer to execute some other instructions when the condition is false, they are put as a part of the else clause.

if 语句后面是一个可选的 else 语句,该语句在布尔表达式为 false 时执行。

An if statement is followed by an optional else statement, which executes when the Boolean expression is false.

Flowchart of if-else Statement

以下流程图表示了 if-else 子句在 C 中的工作方式 −

The following flowchart represents how the if-else clause works in C −

if else statement

请注意,如果你有多个要执行的语句,则 if 中和 else 子句中的大括号是必需的。例如,在以下代码中,我们不需要大括号。

Note that the curly brackets in the if as well as the else clause are necessary if you have more than one statements to be executed. For example, in the following code, we don’t need curly brackets.

if (marks<50)
   printf("Result: Fail\n");
else
   printf("Result: Pass\n");

但是,如果在 ifelse 部分中有不止一个语句,你需要告诉编译器将他们作为复合语句对待。

However, when there are more than one statements, either in the if or in the else part, you need to tell the compiler that they need to be treated as a compound statement.

C if-else Statement Examples

Example: Tax Calculation Using if-else Statement

在下面给出的代码中,计算了员工收入的税款。如果收入低于 10000,则适用 10% 的税率。对于 10000 以上的收入,多余收入收取 15% 的税。

In the code given below, the tax on employee’s income is computed. If the income is below 10000, the tax is applicable at 10%. For the income above 10000, the excess income is charged at 15%.

#include <stdio.h>

int main() {
   int income = 5000;
   float tax;
   printf("Income: %d\n", income);

   if (income<10000){
      tax = (float)(income * 10 / 100);
      printf("tax: %f \n", tax);
   }
   else {
      tax= (float)(1000 + (income-10000) * 15 / 100);
      printf("tax: %f", tax);
   }
}

运行代码并检查其输出:

Run the code and check its output −

Income: 5000
tax: 500.000000

将 income 变量设置为 15000,并再次运行程序。

Set the income variable to 15000, and run the program again.

Income: 15000
tax: 1750.000000

Example: Checking Digit Using if-else Statement

以下程序检查 char 变量存储数字还是非数字字符。

The following program checks if a char variable stores a digit or a non-digit character.

#include <stdio.h>

int main() {
char ch='7';

   if (ch>=48 && ch<=57){
      printf("The character is a digit.");
   }
   else{
      printf("The character is not a digit.");
   }
   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

The character is a digit.

将任何其他字符(如 "*")分配给 "ch",并查看结果。

Assign any other character such as "*" to "ch" and see the result.

The character is not a digit.

Example: if-else Statement Without Curly Braces

考虑以下代码。如果数额大于 100,则打算计算 10% 的折扣,否则没有折扣。

Consider the following code. It intends to calculate the discount at 10% if the amount is greater than 100, and no discount otherwise.

#include <stdio.h>

int main() {
   int amount = 50;
   float discount;
   printf("Amount: %d\n", amount);

   if (amount >= 100)
      discount = amount * 10 / 100;
      printf("Discount: %f \n", discount);
   else
      printf("Discount not applicable\n");

   return 0;
}

该程序在编译过程中显示以下错误 −

The program shows the following errors during the compilation −

error: 'else' without a previous 'if'

编译器将在 if 子句后执行第一个语句,并假设由于下一个语句不是 else (它无论如何都是可选的),因此后续的 printf() 语句是无条件的。但是,下一个 else 没有连接到任何 if 语句,因此产生错误。

The compiler will execute the first statement after the if clause and assumes that since the next statement is not else (it is optional anyway), the subsequent printf() statement is unconditional. However, the next else is not connected to any if statement, hence the error.

Example: if-else Statement Without Curly Braces

也考虑以下代码 −

Consider the following code too −

#include <stdio.h>

int main() {
   int amount = 50;
   float discount, nett;
   printf("Amount: %d\n", amount);

   if (amount<100)
      printf("Discount not applicable\n");
   else
      printf("Discount applicable");
      discount = amount*10/100;
      nett = amount - discount;
      printf("Discount: %f Net payable: %f", discount, nett);

   return 0;
}

该代码不会给出任何编译器错误,但会给出不正确的输出 −

The code doesn’t give any compiler error, but gives incorrect output −

Amount: 50
Discount not applicable
Discount: 5.000000 Net payable: 45.000000

它产生不正确的输出,因为编译器假定 else 子句中只有一个语句,而其余语句都是无条件的。

It produces an incorrect output because the compiler assumes that there is only one statement in the else clause, and the rest of the statements are unconditional.

以上两个代码示例强调了这样一个事实:当 ifelse 中还有多个语句时,必须将它们放在大括号中。

The above two code examples emphasize the fact that when there are more than one statements in the if or else else, they must be put in curly brackets.

为了安全起见,即使对于单个语句,最好总是使用大括号。事实上,它改进了代码的可读性。

To be safe, it is always better to use curly brackets even for a single statement. In fact, it improves the readability of the code.

下面展示了上述问题的正确解决方案 −

The correct solution for the above problem is shown below −

if (amount >= 100){
   discount = amount * 10 / 100;
   printf("Discount: %f \n", discount);
} else {
   printf("Discount not applicable\n");
}

The else-if Statement in C

C 还允许你在程序中使用 else-if 。让我们看看你可以在哪里使用 else-if 子句。

C also allows you to use else-if in the programs. Let’s see where you may have to use an else-if clause.

让我们假设你有如下情况。如果一个条件为真,运行紧随其后的给定代码块。如果条件不真,则运行下一个代码块。但是,如果上述情况都不符合且所有其他情况都失败,最终运行另一个代码块。在这种情况中,你将使用一个 else-if 子句。

Let’s suppose you have a situation like this. If a condition is true, run the given block that follows. If it isn’t, run the next block instead. However, if none of the above is true and all else fails, finally run another block. In such cases, you would use an else-if clause.

Syntax of else-if Statement

下面是 else-if 子句的语法 −

Here is the syntax of the else-if clause −

if (condition){
   // if the condition is true,
   // then run this code
} else if(another_condition){
   // if the above condition was false
   // and this condition is true,
   // then run the code in this block

} else{
   // if both the above conditions are false,
   // then run this code
}

Example of else-if Statement

请看以下示例:

Take a look at the following example −

#include <stdio.h>

int main(void) {
   int age = 15;

   if (age < 18) {
      printf("You need to be over 18 years old to continue\n");
   }else if (age < 21) {
      printf("You need to be over 21\n");
   } else {
      printf("You are over 18 and older than 21 so you can continue \n");
   }
}

运行代码并检查其输出:

Run the code and check its output −

You need to be over 18 years old to continue

现在,为变量“age”提供一个不同的值,并再次运行代码。如果你提供的数值小于 18,你会得到不同的输出。

Now, supply a different value for the variable "age" and run the code again. You will get a different output if the supplied value is less than 18.