ZetCode

C if & else

最后修改于 2023 年 1 月 9 日

C if else 教程介绍了如何使用 if/else 语句在 C 中创建条件和分支。

C if else

if 语句指定了一个代码块的条件执行。如果表达式求值为真,则执行该代码块。如果存在 else 语句且 if 语句的求值为假,则执行 else 后面的代码块。

可以有多个 if/else 语句。

C if else 示例

以下示例演示了使用 if/else 的代码块的条件执行。

if_stm.c
#include <stdio.h>

int main() {
    
    int num = 4;
    
    if (num > 0) {

        printf("The number is positive\n");
    }

    return 0;
}

在示例中,我们有一个简单的条件;如果 num 变量为正数,则将消息“The number is positive”打印到控制台。否则;不打印任何内容。

$ ./if_stm 
The number is positive
if_else.c
#include <stdio.h>

int main() {
    
    int num = -4;
    
    if (num > 4){

        printf("The number is positive\n");
    } else {

        printf("The number is negative\n");
    }

    return 0;
}

现在我们添加了第二个分支。else 语句指定了在 if 条件失败时执行的代码块。

$ ./if_else 
The number is negative

C 多个条件与 else if

我们可以通过额外的 else if 语句拥有多个条件分支。

if_else_if.c
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main() {

    srand(time(NULL));

    int r = rand() % 10 - 5;

    printf("%d\n", r);
    
    if (r > 0){

        printf("The number is positive\n");
    } else if (r == 0) {

        printf("The number is zero\n");
    } else {

        printf("The number is negative\n");
    }
}

在此示例中,我们使用 if else 添加了额外的分支。我们生成介于 -5 和 4 之间的随机值。借助 if & else 语句,我们为所有三个选项打印一条消息。

$ ./if_else_if 
-3
The number is negative
$ ./if_else_if 
0
The number is zero
$ ./if_else_if 
0
The number is zero
$ ./if_else_if 
1
The number is positive
$ ./if_else_if 

我们运行了几次该示例。

在本文中,我们介绍了 C 中的 if else 条件。