前言
学习资料详见中国大学MOOC之西安交大计算机程序设计(C++)课程,传送门。
这一部分主要讲:问题的模块化求解2-特殊函数
题目及解答
1.编写递归函数求数组最大值
编写函数求一个数组中数组元素的最大值,要求必须用递归方法解决。
/*编写函数求一个数组中数组元素的最大值,要求必须用递归方法解决*/
# include <iostream>
using namespace std;
int GetMax(int num[], int a,int b){ //求第a项到第b项的最大值
int c=num[b];
if(b == a) return c;
else{
c = (GetMax(num,a,b-1)>c)?GetMax(num,a,b-1):c;
return c;
}
}
int main(){
//---define---
int num[20];
int n;
int Max;
//---input---
cin>>n;
for (int i=0;i<n;i++)
{
cin>>num[i];
}
//---execute---
Max = GetMax(num, 0, n-1);
//---output---
cout<<Max<<endl;
return 0;
}
2.编写内联函数求矩形的面积和周长
编写函数求矩形的面积和周长,由于算式非常简单,请使用内联函数方式编写,提高程序运行效率
/*编写函数求一个数组中数组元素的最大值,要求必须用递归方法解决*/
# include <iostream>
using namespace std;
inline int GetSize(int a, int b){
int size = a*b;