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

文若2年前技术文章510

程序结构

首先从一个最简单的程序来看 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)


相关文章

Java-API对HDFS的操作(IDEA版)

Java-API对HDFS的操作(IDEA版)

前期工作首先就是安装maven在win系统下不配置hadoop环境,直接运行代码会报错,显示缺少winutils.exe 和 hadoop.dll 两个文件首先添加pom.xml文件  <dep...

Keepalived 高可用解决方案

Keepalived 高可用解决方案

Keepalived 起初是为 LVS 设计的,专门用来监控集群系统中各个服务节点的状态,后来有加入 VRRP 的功能,VRRP 是 Virtual Router Redundancy protoco...

Flink关于HiveCatalog

HiveCatalogHiveCatalog 有两个用途:作为原生 Flink 元数据的持久化存储,以及作为读写现有 Hive 元数据的接口。配置在flink-sql-connector-hive-1...

两款方案详解,企业线下数据库迁移至云上ScyllaDB(1)

两款方案详解,企业线下数据库迁移至云上ScyllaDB(1)

方案一通过扩缩容(上线新节点和下线老节点)方式迁移,这个过程数据库通过数据传输到新节点。整个过程不停机上下线节点的数据传输时存在压力。某个节点存在不可控的故障导致节点无法启动时,数据存在丢失的风险。新...

Linux SSSD同步大量AD用户缓慢

Linux SSSD同步大量AD用户缓慢

1、背景在使用AD + sssd (ad作为ldap)同步用户,其中AD中存在10000+ 用户,同步时,用户信息获取缓慢,导致cdh的namenode 的rpc 队列打高,服务不正常。id 用户达到...

Trino配置yanagishima-23.0(包含编译)

Trino配置yanagishima-23.0(包含编译)

1 环境介绍1.1 本文采用trino 359yanagishima v23.02 编译yanagishima2.1 安装编译yanagishima需要的工具安装编译yanagishima需要的工具w...

发表评论    

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