函数

定义在这里插入图片描述
调用

#include <iostream>
#include <string>
using namespace std;

//定义加法函数 num1,num2为形参
int add(int num1, int num2) {
	int sum = num1 + num2;
	return sum;
}

int main()
{
	//调用函数 a,b为实参
	int a = 32;
	int b = 50;

	int sum = add(a, b);

	cout << sum << endl;

	system("pause"); //固定语句
	return 0;//固定语句
}

在这里插入图片描述
总结:值传递时,形参是修饰不了实参的

#include <iostream>
#include <string>
using namespace std;

//值传递
//定义函数,实现两个数字进行交换函数

//如果函数不需要返回值,声明的时候可以写void
void swap(int num1, int num2) {
	int temp = num1;
	num1 = num2;
	num2 = temp;
	return;
}

int main()
{
	//调用函数 a,b为实参
	int a = 32;
	int b = 50;
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;

	//当我们做值传递的时候,函数的形参发生改变,并不会影响实参
	swap(a, b);

	cout << "a=" << a << endl;
	cout << "b=" << b << endl;

	system("pause"); //固定语句
	return 0;//固定语句
}

函数常见样式

#include <iostream>
#include <string>
using namespace std;

//函数常见样式
//1.无参无返
void test01() {
	cout << "this is test01" << endl;
}

//2.有参无返
void test02(int a) {
	cout << "this is test02" << endl;
}

//3.无参有返
int test03() {
	cout << "this is test03" << endl;
	return 100;
}

//4.有参有返
int test04(int a) {
	cout << "this is test04 a=" << a << endl;
	return a;
}
//如果函数不需要返回值,声明的时候可以写void


int main()
{
	//无参无返函数调用
	test01();

	//有参无返函数调用
	test02(100);

	//无参有返函数调用
	int num1 = test03();
	cout << "num1="<<num1 << endl;

	//有参有返函数调用
	int num2 = test04(100);
	cout << "num2=" << num2 << endl;

	system("pause"); //固定语句
	return 0;//固定语句
}

声明

#include <iostream>
#include <string>
using namespace std;

//函数声明 提前告诉编译器函数的存在
//声明可以写多次,但是定义只能有一次
int max(int a, int b);

int main()
{
	int a = 30;
	int b = 50;

	int c = max(a, b);
	cout << "c = " << c << endl;

	system("pause"); //固定语句
	return 0;//固定语句
}

//定义  比较函数,实现两个整型数字进行比较,返回较大的值
int max(int a, int b) {

	return a > b ? a : b;
}

在这里插入图片描述
1.//1.创建.h后缀名的头文件
在这里插入图片描述
2.//2.创建.cpp后缀名的源文件
在这里插入图片描述
3.//3.在头文件中写函数的声明
4.//4.在源文件中写函数的定义
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值