C++中的函数
一.函数基础
函数定义
返回类型、函数名字、形参列表以及函数体
形参和实参
实参是形参的初始值。
函数返回类型
函数的返回类型不能是数组类型或函数类型,但可以是指向数组或者函数的指针(大多数类型+指针)
静态变量
相当于函数内部只有该函数能用的全局变量
二. 参数传递
传值
传引用
避免拷贝、让函数返回额外信息
传数组
在函数中对数组中的值的修改,会影响函数外面的数组
三. 返回类型和return语句
无返回值函数
函数如果想在它的中间位置提前退出,可以使用return语句。return的这种用法有点类似于我们用break语句退出循环。
有返回值的函数
返回值的类型必须与函数的返回类型相同
四. 函数递归
注意
在一个函数内部,也可以调用函数本身。
五.例题求解
课内例题
1.n 的阶乘
#include <iostream>
using namespace std;
int fact(int n)
{
int res = 1;
for (int i = 1; i <= n; i ++ )
res *= i;
return res;
}
int main()
{
int n;
cin >> n;
cout << fact(n) << endl;
return 0;
}
2.x和y的最大值
#include <iostream>
using namespace std;
int max(int x, int y)
{
if (x > y) return x;
return y;
}
int main()
{
int x, y;
cin >> x >> y;
cout << max(x, y) << endl;
return 0;
}
3.最大公约数
#include <iostream>
using namespace std;
int gcd(int a, int b)
{
for (int i = 1000; i; i -- )
if (a % i == 0 && b % i == 0)
return i;
return -1;
}
int main()
{
int a, b;
cin >> a >> b;
cout << gcd(a, b) << endl;
return 0;
}
4.交换数值
#include <iostream>
using namespace std;
void swap(int& x, int& y)
{
if (x == y) return;
int t = x;
x = y;
y = t;
}
int main()
{
int x, y;
cin >> x >> y;
swap(x, y);
cout << x << ' ' << y << endl;
return 0;
}
5.打印数字
#include <iostream>
using namespace std;
const int N = 1010;
void print(int a[], int size)
{
for (int i = 0; i < size; i ++ )
cout << a[i] << ' ';
cout << endl;
}
int main()
{
int n, size;
int a[N];
cin >> n >> size;
for (int i = 0