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

相关推荐
Algo-hx4 分钟前
C++编程基础(九):预处理指令
c++
凌康ACG7 小时前
Sciter之c++与前端交互(五)
c++·sciter
郝学胜-神的一滴9 小时前
Linux命名管道:创建与原理详解
linux·运维·服务器·开发语言·c++·程序人生·个人开发
晚风(●•σ )9 小时前
C++语言程序设计——11 C语言风格输入/输出函数
c语言·开发语言·c++
恒者走天下11 小时前
秋招落定,拿到满意的offer,怎么提高自己实际的开发能力,更好的融入团队
c++
天若有情67311 小时前
【c++】手撸C++ Promise:从零实现通用异步回调组件,支持链式调用+异常安全
开发语言·前端·javascript·c++·promise
学困昇11 小时前
C++中的异常
android·java·c++
合作小小程序员小小店12 小时前
桌面安全开发,桌面二进制%恶意行为拦截查杀%系统安全开发3.0,基于c/c++语言,mfc,win32,ring3,dll,hook,inject,无数据库
c语言·开发语言·c++·安全·系统安全
Codeking__12 小时前
C++ 11 atomic 原子性操作
开发语言·c++
crescent_悦12 小时前
PTA L1-020 帅到没朋友 C++
数据结构·c++·算法