C++基础--函数

1. 定义

#include<iostream>
using namespace std;

/*返回值类型 函数名(参数列表)
{
	函数体语句
	return表达式
}
*/
int Add(int num1,int num2){
	int sum = num1+num2;
	return sum;
}

int main(){
	
	int num1 =0;
	int num2 =0;
	cout << "请输入num1:" << endl;
	cin>>num1;
	cout << "请输入num2:" << endl;
	cin>>num2;
	int c = Add(num1,num2);
	cout << "num1与sum2之和为:"<< c <<endl;
	system("pause");
	return 0;
}

2.常见样式

#include<iostream>
using namespace std;

// 1.无参无返
void test01(){
	cout << "this is test01" << endl;
}
// 2.有参无返
void test02(int a){
	cout << "this is test02, a=" << a << endl;
}
// 3.无参有返
int test03(){
	cout << "this is test03, ";
	int a =10;
	return a;
}
//4.有参有返
int test04(int a){
	cout << "this is test04, ";
	return a;
}

int main(){

	test01();
	test02(5);
	int num1=test03();
	cout << num1 <<endl;
	int num2 =test04(1000);
	cout << num2 <<endl;
	system("pause");
	return 0 ;
}

3. 声明

#include<iostream>
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. 值传递

#include<iostream>
using namespace std;
//值传递时,形参发生任何改变都不会影响实参
//实现两个数字进行交换函数
void swap(int num1,int num2){
	cout << num1<<" "<< num2 <<endl;
	int temp = num1;
		num1 = num2;
		num2 = temp;
	cout << num1<<" "<< num2 <<endl;
}

int main(){
	
	int num1 =0;
	int num2 =0;
	cout << "请输入num1:" << endl;
	cin>>num1;
	cout << "请输入num2:" << endl;
	cin>>num2;
	swap(num1,num2);
	system("pause");
	return 0;
}

5. 分文件编写

步骤:
(1)创建xxx.h文件,进行函数声明
(2)创建xxx.cpp文件,进行函数定义
(3)main文件,加上#include “xxx.h”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值