C++程序设计----->函数
函数在编程中是非常重要的,C++中包括内部函数和外部函数。
1.自定义函数
#定义函数
函数类型 函数名(函数的参数)
{
函数作用代码
}
#调用函数
int main()
{
add();
return 0;
}
列题1:定义一个函数,输出helloworld
#include<iostream>
using namesapce std;
//1.函数的定义
void helloworld()
{
cout<<"hello world";
}
int main()
{
//2.函数的调用
helloworld();
return 0;
{
列题2:定义一个比较大小的函数,输出较大值
#include<iostream>
using namespace std;
int compare(int a,int b)
{
if(a>b)
{
cout<<a;
}
else if(b>a)
{
cout<<b;
}
else if(a=b)
{
cout<<a<<b;
}
}
int main()
{
int c,d;
cin>>c>>d;
compare(c,d);
return 0;
}
3.函数可分为有参函数,无参函数,及有返回值函数,无返回值函数。在这里有两个比较重要的函数知识点。
a.数组作为函数的参数
b.递归调用
例题3.求学生的平均身高
#include<iostream>
using namespace std;
float average(float array[],int n)
{
int i;
float aver,sum=0;
for(i=0;i<n;i++)
{
sum +=array[i];
}
aver=sum/n
return (aver);
}
int main()
{
float height[100],aver;
int i,n;
cin>>n;
for(i=0;i<n;i++)
{
cin>>height[i];
{
aver=average(height,n);
cout<<aver;
return 0;
}
递归调用
题目:有五个人坐在一起,问第五个人多少岁?他说比第四个人大两岁,
问第四个人的岁数,他说比第三个人大2岁,问第三个人,他比第二个人大两岁,
第二个人说,比第一个人大两岁,最后一个人说,他10岁,输入第n个人,
输出他的年龄
#include<iostream>
using namespace std;
int age(int n)
{
int t;
if(n==1)
{
f=10;
}
else
{
f=age(n-1)+2;
}
return f;
}
int main()
{
int a;
cii=n>>a;
int b;
b=age(a);
cout<<b;
return 0;
}
``