alog.h
#include <IOSTREAM>
using namespace std;
// 以下为函数模板 注意!函数模板必须紧跟在template<typename T>之后定义!
template<typename T>
T min(T a, T b)
{
T min;
if (a > b)
{
min = b;
}
else
min = a;
return min;
}
//递归的思想在于,已知首项和规律,求若干项的答案;
//设计思路如下:要从若干项中的最后一项开始考虑,总结出通项公式,逆推回溯回来,
//若成立,则设计代码成功!
//需要用递归的思想来解决年龄计算问题;
int age(int n)
{
int c;
if (n==1)
{
c = 10;
}
else
{
c = age(n-1)+2;
}
return c;
}
//用递归方法来解决n!的问题;
int sort(int n)
{
int sum;
if (n == 1|| n == 0)
{
sum = 1;
}
else
{
sum = sort(n-1)*n; //1*2*3*4
}
return sum;
}
// 内置函数的设计与理解
// 加关键字inline,内置函数相当于用代码来代替函数,例如max(a,b);
// 调用max(a,b)时候,将max函数里面的代码复制进主函数。
// 内置函数不能有循环控制语句。inline关键字在定义函数时候可以写,也可以不写;
// 在声明时候则一定要写;
inline int max(int a,int b)
{
int max;
if (a > b)
{
max = a;
}
else
max = b;
return max;
}
// 以下为重载函数,在重载函数中,参数个数,参数类型,和参数顺序至少要有一种不同,否则不合法!
double max(double a,double b)
{
double max;
if (a > b)
{
max = a;
}
else
max = b;
return max;
}
float max(float a,float b)
{
float max;
if (a > b)
{
max = a;
}
else
max = b;
return max;
}
// 有默认参数的函数:当实参无值传递过来的话,用函数的默认参数,如果有实参值传过来用实参值!
double area(double r = 6.50)
{
double pai = 3.14;
double sum = pai *(r * r);
return sum;
}
main.cpp
#include "alog.h"
int main()
{
int n;
cout<<"请输入要计算第几个人的年龄:"<<endl;
cin>>n;
cout<<"第"<<n<<"个人的年龄是:"<<age(n)<<endl;
int m;
cout<<"请输入要计算的阶乘数:"<<endl;
cin>>m;
cout<<m<<"!的阶乘是:"<<sort(m)<<endl;
cout<<"在 m 和 n 中: max = "<<max(m,n)<<endl;
return 0;
}