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

相关推荐
从零开始的代码生活_12 小时前
C++ 内存管理:从内存分区到 new/delete 底层原理
开发语言·c++·后端
aaPIXa62213 小时前
C++ 用 13 条规则让模型写出安全现代 C++
java·c++·安全
枕星而眠14 小时前
【数据结构】红黑树入门指南
运维·数据结构·c++·后端
2601_9498177214 小时前
C++指针与引用深度精讲:底层原理、差异对比与高阶实战陷阱
java·jvm·c++
烟锁池塘柳016 小时前
【C/C++】解决C++控制台输出中文乱码问题
c语言·开发语言·c++
zh路西法16 小时前
【10天速通Navigation2】(九):LQR最优控制器的原理推导与Nav2插件实现
c++·ros2·最优控制·lqr·navigation2
粘稠的浆糊16 小时前
[AtCoder - abc465_d ]X to Y题解
数据结构·c++·算法
誰能久伴不乏16 小时前
C++11 随机数生成——告别 rand()
开发语言·c++
KouFiee17 小时前
同名隐藏基础
开发语言·c++
从零开始的代码生活_17 小时前
C++ string 详解:常用接口、字符串算法与深拷贝实现
开发语言·c++·后端·学习·算法