C++ 编程:程序组成部分 & 函数 & 输入

文若2年前技术文章737

程序结构

首先从一个最简单的程序来看 C++ 程序结构:

截屏2023-06-09 14.53.09.png

第一部分:#include <iostream> 专业名词叫:预处理器编译指令 其实效果就类似于导包;

第二部分:main() 程序的主体 C++ 程序是从这里开始运行,调用其它功能函数;

第三部分:std::cout << "Hello World" << std::endl; 程序的功能,这行就是输出 Hello Word;

第四部分:return 0 在 C++ 中,除非明确声明了不返回值,否则函数必须返回一个值。main( ) 也是函数,且总是返回 一个整数。这个整数值被返回给操作系统,根据应用程序的性质,这可能很有用,因为大多数操作系 统都提供了查询功能,让用户能够获悉正常终止的应用程序的返回值。在很多情况下,一个应用程序被 另一个应用程序启动,而父应用程序(启动者)想知道子应用程序(被启动者)是否成功地完成了其任务。程序员可使用 main( )的返回值向父应用程序传递成功或错误状态。也就是说我们可以通过反回 code 让其它程序获得程序的运行情况,例如我们使用 Python 来调用系统 mv 程序,此时我们可以返回的 code 来判断程序是否出现异常。

截屏2023-06-09 14.53.18.png


命名空间

名称空间的概念,请看下方代码示例:

// Pre-processor directive
#include <iostream>

// Start of your program
int main()
{
  // Tell the compiler what namespace to look in
  using namespace std;

  /* Write to the screen using cout */
  cout << "Hello World" << endl;

  // Return a value to the OS
  return 0;
}

using namespace std; 这个可以理解为 Python 中的 from xxx import xxx

函数

函数定义也是比较简单的,首先你得先确定返回的数据类型,返回的数据必须是该类型。

#include <iostream>
using namespace std;

// Function declaration
int DemoConsoleOutput();

int main()
{
  // Function call
DemoConsoleOutput();

return 0;
}

// Function definition
int DemoConsoleOutput()
{
cout << "This is a simple string literal" << endl;
cout << "Writing number five: " << 5 << endl;
cout << "Performing division 10 / 5 = " << 10 / 5 << endl;
cout << "Pi when approximated is 22 / 7 = " << 22 / 7 << endl;
cout << "Pi actually is 22 / 7 = " << 22.0 / 7 << endl;

return 0;
}

上方 Code 就是一个非常简单的函数调用。

## 输入 与 输出:

#include <iostream>

using namespace std;

int input_df() {
   int InputNumber1;
   cout << "第一个数: ";
   cin >> InputNumber1;

int InputNumber2;
   cout << "第二个数: ";
   cin >> InputNumber2;

   cout << "return: " << InputNumber1 * InputNumber2 << endl;
   return 0;
}

int main() {
   std::cout << "Hello Word\n";
   input_df();
   return 0;
}

要将简单的文本数据写入到控制台,可使用 std::cout(读作 standard see-out);要从控制台读取文 本和数字,可使用 std::cin(读作 standard see-in)


相关文章

Hbase预分区

Hbase预分区

HBase 的数据物理存储格式为多维稀疏排序 Map, 由 key 及 value 组成:key 的构成: rowkey+column family+column qualifier+timestam...

trino组件对接alluxio(三)

trino组件对接alluxio(三)

本文是基于已经部署了trino和alluxio的基础上,进行的trino与alluxio的组件对接,alluxio已经开启了高可用模式。安装部署1、增加alluxio配置在core-site.xml和...

迁移Cloudera Manager节点

迁移Cloudera Manager节点

1.概述1.CDH环境已搭建并正常运行2.旧Cloudera Manager节点包含Cloudera Manager Server(即cloudera-scm-server)服务和Cloudera M...

MySQL运维实战(4.9) SQL_MODE之NO_UNSIGNED_SUBTRACTION

在mysql数据库中,unsigned表示不存负数,如果unsigned类型的字段作运算,得到的结果为负数,SQL会报错。mysql> create table t...

kubernetes HPA

kubernetes HPA

Horizontal Pod Autoscaling 可以根据 CPU 利用率自动伸缩一个 ReplicaSet、Deployment 或者中的 Pod 数量cat hpa-deploy.yaml a...

大数据集群部署规划(三)节点选配方案

节点部署原则适用场景组网规则管理节点、控制节点和数据节点分开部署(此方案至少需要8个节点,manager为部署商业化大数据集群时所需例如:hdp,cdh等)core × 11 + worker × n...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。