C++ 程序:查找最大数

C++C++Beginner
立即练习

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

介绍

在本实验中,我们将编写一个 C++ 程序来找出三个数中的最大值。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("C++")) -.-> cpp/BasicsGroup(["Basics"]) cpp(("C++")) -.-> cpp/ControlFlowGroup(["Control Flow"]) cpp(("C++")) -.-> cpp/IOandFileHandlingGroup(["I/O and File Handling"]) cpp(("C++")) -.-> cpp/SyntaxandStyleGroup(["Syntax and Style"]) cpp/BasicsGroup -.-> cpp/variables("Variables") cpp/BasicsGroup -.-> cpp/data_types("Data Types") cpp/ControlFlowGroup -.-> cpp/conditions("Conditions") cpp/ControlFlowGroup -.-> cpp/if_else("If...Else") cpp/IOandFileHandlingGroup -.-> cpp/output("Output") cpp/IOandFileHandlingGroup -.-> cpp/user_input("User Input") cpp/IOandFileHandlingGroup -.-> cpp/files("Files") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("Code Formatting") subgraph Lab Skills cpp/variables -.-> lab-96240{{"C++ 程序:查找最大数"}} cpp/data_types -.-> lab-96240{{"C++ 程序:查找最大数"}} cpp/conditions -.-> lab-96240{{"C++ 程序:查找最大数"}} cpp/if_else -.-> lab-96240{{"C++ 程序:查找最大数"}} cpp/output -.-> lab-96240{{"C++ 程序:查找最大数"}} cpp/user_input -.-> lab-96240{{"C++ 程序:查找最大数"}} cpp/files -.-> lab-96240{{"C++ 程序:查找最大数"}} cpp/code_formatting -.-> lab-96240{{"C++ 程序:查找最大数"}} end

创建新文件

我们将在 ~/project 目录下使用以下命令创建一个名为 main.cpp 的新文件:

touch ~/project/main.cpp

包含必要的头文件

我们需要包含 iostreamcstdlib 头文件,以便使用 coutcinsystem 函数。

#include <iostream>
#include <cstdlib>

创建 main() 函数

添加以下代码以创建 main() 函数:

int main() {
  // code will go here
  return 0;
}

声明三个 float 变量

我们需要声明三个 float 变量来存储用户输入的三个数字。

float n1, n2, n3;

提示用户输入

我们将使用 cout 函数提示用户输入三个数字,并使用 cin 函数将这些数字存储到我们刚刚声明的变量中。

std::cout << "Enter three numbers: ";
std::cin >> n1 >> n2 >> n3;

确定最大数

我们将使用一系列 if 语句来确定并输出三个数中的最大值。

if (n1 >= n2 && n1 >= n3) {
  std::cout << "Largest number: " << n1;
}
if (n2 >= n1 && n2 >= n3) {
  std::cout << "Largest number: " << n2;
}
if (n3 >= n1 && n3 >= n2) {
  std::cout << "Largest number: " << n3;
}

运行程序

使用以下命令编译并运行程序:

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

完整代码

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

#include <iostream>
#include <cstdlib>

int main() {
  float n1, n2, n3;
  std::cout << "Enter three numbers: ";
  std::cin >> n1 >> n2 >> n3;
  if (n1 >= n2 && n1 >= n3) {
    std::cout << "Largest number: " << n1;
  }
  if (n2 >= n1 && n2 >= n3) {
    std::cout << "Largest number: " << n2;
  }
  if (n3 >= n1 && n3 >= n2) {
    std::cout << "Largest number: " << n3;
  }
  return 0;
}

总结

在本实验中,我们编写了一个 C++ 程序来找出三个数中的最大值。我们学习了如何使用 if 语句来比较值,以及如何使用 coutcin 提示用户输入。我们还学习了如何在终端中编译和运行 C++ 程序。