2021-02-02

函数

函数的定义一般为以下5个步骤:

  1. 返回值类型
  2. 函数名
  3. 参数表列
  4. 函数体语句
  5. return表达式
/*函数定义和调用*/
#include <iostream>
#include <string>
#include <cmath>
using namespace std;

//函数定义
int add(int num1, int num2)
{
	int sum = num1 + num2;
	return sum;
}

int main()
{
	//在main函数中调用add
	int a = 10;
	int b = 10;
	int c = add(a, b);
	cout << "c=" << c << endl;
	system("pause");
	return 0;
}

/*值传递*/
#include <iostream>
#include <string>
#include <cmath>
using namespace std;

//定义一个函数,实现两个数字进行交换
//如果函数不需要返回值,声明的时候可以写void
void swap(int num1, int num2)
{
	cout << "交换前:" << endl;
	cout << "num1=" << num1 << endl;
	cout << "num2=" << num2 << endl;
	int temp = num1;
	num1 = num2;
	num2 = temp;
	cout << "交换后:" << endl;
	cout << "num1=" << num1 << endl;
	cout << "num2=" << num2 << endl;
	//return;返回值不需要的时候可以不写return
}

int main()
{
	//在main函数中调用add
	int a = 10;
	int b = 20;
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
	//当我们做值传递的时候,形参发生改变不会影响实参的值
	swap(a, b);
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
	system("pause");
	return 0;
}

函数的常见样式

  1. 无参无返
  2. 无参有返
  3. 有参无返
  4. 有参有返
/*函数常见样式*/
#include <iostream>
#include <string>
#include <cmath>
using namespace std;

//无参无返
void test01()
{
	cout << "this is test01" << endl;
}
//有参无返
void test02(int a)
{
	cout << "this is test02 a=" << a << endl;
}
//无参有返
int test03()
{
	cout << "this is test03" << endl;
	return 1000;
}
//有参有返
int test04(int a)
{
	cout << "this is test04 a=" << a << endl;
	return a;
}

int main()
{
	//无参无返函数调用
	test01();
	//有参无返函数调用
	test02(100);
	//无参有返函数调用
	int num1 = test03();
	cout << "num1=" << num1 << endl;
	//有参有返函数调用
	int num2 = test04(10000);
	cout << "num2=" << num2 << endl;
	system("pause");
	return 0;
}
/*函数声明*/
#include <iostream>
#include <string>
#include <cmath>
using namespace std;

//比较函数,实现两个整型数字进行比较,返回较大值
//提前告诉编译器,函数已经存在,可以利用函数声明
//声明可以有多次,但是定义只能有一次

//函数的声明
int max(int a, int b);

int main()
{
	int a = 10;
	int b = 20;
	cout << max(a, b) << endl;
	system("pause");
	return 0;
}

//定义
int max(int a, int b)
{
	return a > b ? a : b;
}

函数的分文件编写

一般分为4步:

  1. 创建后缀名为.h的头文件
  2. 创建后缀名为.cpp的源文件
  3. 在头文件中写函数的声明
  4. 在源文件中写函数的定义

swap.h

#include <iostream>
using namespace std;
//实现交换两个数字的函数
void swap(int a, int b);

swap.cpp

#include "swap.h"
//定义
void swap(int a, int b)
{
	int temp = a;
	a = b;
	b = temp;
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
}

main.cpp

/*函数的分文件编写*/
#include <iostream>
#include "swap.h"
using namespace std;

int main()
{
	int a = 10;
	int b = 20;
	swap(a,b);
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值