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++后台高级服务器课程

相关推荐
塔尖尖儿8 分钟前
For循环中++i与i++有什么不一样?
c++
Ralph_Y13 分钟前
C++虚继承
开发语言·c++
ZzZz_ing34 分钟前
2026 - 零碎知识随记录
c++
SweetCode35 分钟前
【无标题】
开发语言·c++·算法
王老师青少年编程1 小时前
信奥赛C++提高组csp-s之拓扑排序详解
c++·算法·拓扑排序·csp·信奥赛·csp-s·提高组
xie_pin_an1 小时前
C++ 从入门到进阶:核心知识与实战指南
java·c++·算法
No0d1es1 小时前
2025年12月 GESP CCF编程能力等级认证C++八级真题
开发语言·c++·青少年编程·gesp·ccf
fqbqrr2 小时前
2601C++,概念与约束及推导本
c++
xiaowu0802 小时前
C#调用 C++ DLL 加载地址方式选择
开发语言·c++·c#
转基因2 小时前
C++的IO流
开发语言·c++