第三章部分例题(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;
}

 

posted on 2023-04-21 10:27  石铁生  阅读(25)  评论(1)    收藏  举报