从三个给定数字中查找最大值

C++C++Beginner
立即练习

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

介绍

在本实验中,我们将编写一个 C++ 程序,该程序将从用户那里获取三个数字作为输入,并使用 if/else 语句找出其中的最大值。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/FunctionsGroup(["`Functions`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/ControlFlowGroup -.-> cpp/conditions("`Conditions`") cpp/FunctionsGroup -.-> cpp/function_parameters("`Function Parameters`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/IOandFileHandlingGroup -.-> cpp/user_input("`User Input`") cpp/IOandFileHandlingGroup -.-> cpp/files("`Files`") subgraph Lab Skills cpp/variables -.-> lab-96192{{"`从三个给定数字中查找最大值`"}} cpp/conditions -.-> lab-96192{{"`从三个给定数字中查找最大值`"}} cpp/function_parameters -.-> lab-96192{{"`从三个给定数字中查找最大值`"}} cpp/output -.-> lab-96192{{"`从三个给定数字中查找最大值`"}} cpp/user_input -.-> lab-96192{{"`从三个给定数字中查找最大值`"}} cpp/files -.-> lab-96192{{"`从三个给定数字中查找最大值`"}} end

创建新文件

~/project 目录下创建一个名为 main.cpp 的新文件。

touch ~/project/main.cpp

包含必要的库

我们需要包含 iostream 库以支持输入和输出操作。

#include <iostream>

编写一个函数来查找最大值

我们将编写一个函数,该函数接收三个数字作为输入并返回其中的最大值。我们将使用 if/else 语句来比较这三个数字并找出最大值。

int findMax(int num1, int num2, int num3) {
    int max = num1;

    if (num2 > max) {
        max = num2;
    }

    if (num3 > max) {
        max = num3;
    }

    return max;
}

编写主函数

在主函数中,我们将提示用户输入三个数字,然后调用 findMax 函数来查找最大值。

int main() {
    int num1, num2, num3;

    std::cout << "Enter the three numbers: ";
    std::cin >> num1 >> num2 >> num3;

    std::cout << "The maximum number is: " << findMax(num1, num2, num3) << std::endl;

    return 0;
}

编译并运行程序

要编译程序,请打开终端并导航到 ~/project 目录。然后运行以下命令:

g++ main.cpp -o main && ./main

你将看到以下输出:

Enter the three numbers: 10 20 30
The maximum number is: 30

完整代码

以下是 main.cpp 文件的完整代码:

#include <iostream>

int findMax(int num1, int num2, int num3) {
    int max = num1;

    if (num2 > max) {
        max = num2;
    }

    if (num3 > max) {
        max = num3;
    }

    return max;
}

int main() {
    int num1, num2, num3;

    std::cout << "Enter the three numbers: ";
    std::cin >> num1 >> num2 >> num3;

    std::cout << "The maximum number is: " << findMax(num1, num2, num3) << std::endl;

    return 0;
}

总结

在本实验中,我们学习了如何创建一个 C++ 程序,该程序可以使用 if/else 语句从三个给定的数字中找出最大值。我们还学习了如何编写一个函数来查找最大值,以及如何使用输入/输出语句提示用户输入数字并显示结果。

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