第三章部分例题(6)
例3-13
值传递与引用传递的比较
设计思路:通过函数对数值进行改变观察值传递与应用传递后原数值的变化
代码:
#include <iostream> #include<iomanip> using namespace std; void fiddle(int in1,int &in2) { in1+=100; in2+=100; cout<<"The values are "; cout<<setw(5)<<in1; cout<<setw(5)<<in2<<endl; } int main() { int v1=7,v2=12; cout<<"The values are "; cout<<setw(5)<<v1; cout<<setw(5)<<v2<<endl; fiddle(v1,v2); cout<<"The values are "; cout<<setw(5)<<v1; cout<<setw(5)<<v2<<endl; return 0; }
例·3-14
题目描述:内联函数应用举例
代码实现:
#include <iostream> using namespace std; const double PI=3.14159265358979; inline double calArea(double r) { return PI*r*r; } int main() { double r=3.0; double Area=calArea(r); cout<<Area<<endl; return 0; }
例3-15
题目描述:带默认形参值的函数举例
本程序的功能室计算长方体的体积,子函数getVolume是计算体积的函数,有三个形参:length(长),width(宽),height(高),其中width和height带有默认值。主函数中以不同形式调用getVolume函数,分析程序的运行结果
#include<iostream> using namespace std; int getVolume(int length,int width=1,int height=1) { return length*width*height; } int main() { int x=10,y=12,z=15; cout<<"Some box data is"; cout<<getVolume(x,y,z)<<endl; cout<<"Some box data is"; cout<<getVolume(x,y)<<endl; cout<<"Some box data is"; cout<<getVolume(x)<<endl; return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了