使用全局变量查找最大值和最小值

CCBeginner
立即练习

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

介绍

在本实验中,我们将学习如何在 C 编程中使用全局声明来找出两个输入数字中的最大值和最小值。与局部变量不同,全局变量可以被程序中的任何函数访问和修改。我们将使用全局变量来存储输入数字并解决问题。

注意:你需要自己创建文件 ~/project/main.c 来练习编码,并学习如何使用 gcc 编译和运行它。

cd ~/project
## 创建 main.c
touch main.c
## 编译 main.c
gcc main.c -o main
## 运行 main
./main

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c/BasicsGroup -.-> c/variables("`Variables`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/UserInteractionGroup -.-> c/output("`Output`") subgraph Lab Skills c/variables -.-> lab-123273{{"`使用全局变量查找最大值和最小值`"}} c/if_else -.-> lab-123273{{"`使用全局变量查找最大值和最小值`"}} c/user_input -.-> lab-123273{{"`使用全局变量查找最大值和最小值`"}} c/output -.-> lab-123273{{"`使用全局变量查找最大值和最小值`"}} end

声明全局变量

首先,我们需要在 main 函数外部声明两个全局变量 ab。我们将把输入的数字存储在这些变量中。

#include <stdio.h>
int a, b;

从用户获取输入值

在这一步中,我们将使用 scanf() 函数从用户获取两个整数值,并将它们存储在变量 ab 中。

int main()
{
    printf("Enter two numbers to find the largest and smallest numbers: ");
    scanf("%d %d", &a, &b);
}

找出最大值和最小值

为了找出最大值和最小值,我们将使用 if...else 语句来比较 ab 的值。如果 a 大于 b,则 a 是最大值,b 是最小值,反之亦然。如果 ab 相等,则两者相同。

    if(a > b)
    {
        printf("The largest number is %d\n", a);
        printf("The smallest number is %d\n", b);
    }
    else if(a < b)
    {
        printf("The largest number is %d\n", b);
        printf("The smallest number is %d\n", a);
    }
    else
    {
        printf("Both numbers are equal\n");
    }

完成程序

最后,我们将添加一些打印语句来显示输出信息,并返回 0 以表示程序成功执行。

#include <stdio.h>
int a, b;

int main()
{
    printf("Enter two numbers to find the largest and smallest numbers: ");
    scanf("%d %d", &a, &b);

    if(a > b)
    {
        printf("The largest number is %d\n", a);
        printf("The smallest number is %d\n", b);
    }
    else if(a < b)
    {
        printf("The largest number is %d\n", b);
        printf("The smallest number is %d\n", a);
    }
    else
    {
        printf("Both numbers are equal\n");
    }
    return 0;
}

总结

在本实验中,我们学习了如何在 C 编程中使用全局声明来找出两个输入数字中的最大值和最小值。我们声明了两个全局变量 ab 来存储输入数字,并通过比较它们的值来确定最大值和最小值。通过练习这个程序,学生可以学习如何声明全局变量并在 C 编程中使用基本的条件语句。

您可能感兴趣的其他 C 教程