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

相关推荐
AlexMercer10121 小时前
【C++】二、数据类型 (同C)
c语言·开发语言·数据结构·c++·笔记·算法
小灰灰爱代码1 小时前
C++——求3个数中最大的数(分别考虑整数、双精度数、长整数的情况),用函数模板来实现。
开发语言·c++·算法
BeyondESH3 小时前
Linux线程同步—竞态条件和互斥锁(C语言)
linux·服务器·c++
豆浩宇3 小时前
Halcon OCR检测 免训练版
c++·人工智能·opencv·算法·计算机视觉·ocr
WG_173 小时前
C++多态
开发语言·c++·面试
Charles Ray5 小时前
C++学习笔记 —— 内存分配 new
c++·笔记·学习
重生之我在20年代敲代码5 小时前
strncpy函数的使用和模拟实现
c语言·开发语言·c++·经验分享·笔记
迷迭所归处10 小时前
C++ —— 关于vector
开发语言·c++·算法
CV工程师小林11 小时前
【算法】BFS 系列之边权为 1 的最短路问题
数据结构·c++·算法·leetcode·宽度优先
white__ice12 小时前
2024.9.19
c++