*C++程序设计----->函数

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;
}









``

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

code.xinxixue.top

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值