C++中编写接受多个参数的函数

C++中编写接受多个参数的函数

C++的函数可以有多个参数,并不复杂,假设我们要编写一个计算圆柱表面积的程序。

首先,计算圆柱面积的公式如下:

Area of Cylinder = Area of top circle + Area of bottom circle + Area of Side

= Pi * radius^2 + Pi * radius ^2 + 2 * Pi * radius * height

= 2 * Pi * radius^2 + 2 * Pi * radius * height

计算圆柱面积时,需要两个变量---半径和高度。编写计算圆柱表面积的函数时,至少需要在函数声明的形参列表中指定两个形参。为此,需要用逗号分隔形参,如下面的示例程序所示:

cpp 复制代码
#include <iostream>
using namespace std;

const double Pi = 3.14159265;

// Declaration contains two parameters
double SurfaceArea(double radius, double height);

int main()
{
    cout << "Enter the radius of the cylinder: ";
    double radius = 0;
    cin >> radius;
    cout << "Enter the height of the cylinder: ";
    double height = 0;
    cin >> height;

    cout << "Surface area: " << SurfaceArea(radius, height) << endl;

    return 0;
}

double SurfaceArea(double radius, double height)
{
    double area = 2 * Pi * radius * radius + 2 * Pi * radius * height;
    return area;
}

输出:

复制代码
Enter the radius of the cylinder: 3
Enter the height of the cylinder: 6.5
Surface Area: 179.071

分析:

第 6 行是函数 SurfaceArea()的声明,其中包含两个用逗号分隔的形参---radius 和 height,它们的类型都是 double。第 22~26 行是函数 SurfaceArea()的定义,即实现。正如您看到的, 使用输入参数 radius 和 height 计算了表面积,将其存储在局部变量 area 中,再将 area 返回给调用者。

注意:

复制代码
函数形参类似于局部变量,它们只在当前函数内部可用。因此,在示例程序中,函数 SurfaceArea()的形参 radius 和 height 是函数 main() 中同名变量的拷贝。

该文章会更新,欢迎大家批评指正。

推荐一个零声学院的C++服务器开发课程,个人觉得老师讲得不错,

分享给大家:Linux,Nginx,ZeroMQ,MySQL,Redis,

fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,

TCP/IP,协程,DPDK等技术内容

点击立即学习:C/C++后台高级服务器课程

相关推荐
鱼很腾apoc44 分钟前
【学习篇】第20期 超详解 C++ 多态:从语法规则到底层原理
java·c语言·开发语言·c++·学习·算法·青少年编程
不吃土豆的马铃薯2 小时前
4.SGI STL 二级空间配置器 allocate 与_S_refill 源码解析
c语言·开发语言·c++·dreamweaver·内存池
fufu03113 小时前
vscode配置C/C++环境,用GDB调试简单程序分享
开发语言·c++
水云桐程序员4 小时前
C++变量的概念及用法
开发语言·c++
水饺编程4 小时前
第5章,[Win32 章节] :几种典型的颜色
c语言·c++·windows·visual studio
Larry_Yanan5 小时前
QML面试常见问题(一)QML中组件呈现方式的方法有哪些
开发语言·c++·qt·ui·面试
杨校5 小时前
杨校老师课堂之C++的位运算应用专项训练
开发语言·c++
j7~5 小时前
【MYSQL】在Centos7和ubuntu22.04环境下安装
数据库·c++·mysql·ubuntu·centos
代码中介商5 小时前
C++ STL 容器完全指南(三):deque、list 与 map 深度详解
开发语言·c++
eggrall6 小时前
Linux进程信号——像收快递一样理解 Linux 信号
linux·开发语言·c++