在 C 编程中使用 If-Else 语句

CCBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在 C 编程中,if else 语句用于根据条件执行代码块。如果 if 语句中指定的条件为真,则执行 if 块中的代码,否则执行 else 块中的代码。在本实验中,你将学习如何在 C 编程语言中使用 if else 语句。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("C")) -.-> c/BasicsGroup(["Basics"]) c(("C")) -.-> c/ControlFlowGroup(["Control Flow"]) c(("C")) -.-> c/FileHandlingGroup(["File Handling"]) c(("C")) -.-> c/UserInteractionGroup(["User Interaction"]) c/BasicsGroup -.-> c/variables("Variables") c/ControlFlowGroup -.-> c/if_else("If...Else") c/FileHandlingGroup -.-> c/create_files("Create Files") c/UserInteractionGroup -.-> c/user_input("User Input") c/UserInteractionGroup -.-> c/output("Output") subgraph Lab Skills c/variables -.-> lab-123265{{"在 C 编程中使用 If-Else 语句"}} c/if_else -.-> lab-123265{{"在 C 编程中使用 If-Else 语句"}} c/create_files -.-> lab-123265{{"在 C 编程中使用 If-Else 语句"}} c/user_input -.-> lab-123265{{"在 C 编程中使用 If-Else 语句"}} c/output -.-> lab-123265{{"在 C 编程中使用 If-Else 语句"}} end

创建 main.c 文件

~/project/ 目录下创建一个名为 main.c 的文件,并包含必要的头文件。

#include <stdio.h>

从用户获取输入

在这一步中,我们将使用 scanf 函数从用户获取一个数字,并将其存储在变量 number 中。

int number;
printf("Please enter a number:\n");
scanf("%d", &number);

使用 if else 语句

在这一步中,我们将使用 if else 语句来检查输入的数字是否小于、等于或大于 100,并向用户显示相应的消息。

if(number < 100)
{
    printf("Number is less than 100!\n");
}
else if(number == 100)
{
    printf("Number is 100!\n");
}
else
{
    printf("Number is greater than 100!\n");
}

整合所有代码

将上述所有步骤整合到 main 函数中。

#include <stdio.h>

int main()
{
    int number;
    printf("Please enter a number:\n");
    scanf("%d", &number);

    if(number < 100)
    {
        printf("Number is less than 100!\n");
    }
    else if(number == 100)
    {
        printf("Number is 100!\n");
    }
    else
    {
        printf("Number is greater than 100!\n");
    }

    return 0;
}

总结

在本实验中,你学习了如何在 C 编程语言中使用 if else 语句来根据条件执行代码块。你还学习了 if else 语句的语法、如何从用户获取输入以及如何向用户显示输出。