# C++学习(二)_函数中的重要知识点

## 1.函数的重要性

##### 恰恰相反，函数的使用让程序的可读性、可维护性更强。同时函数可以被反复调用，也提高了模块的可复用性。

不使用函数:
#include<iostream>

using namespace std;

//计算1/1!--1/10!
int main()
{
double sum = 0;

for(int i = 1; i <= 10; i++){
double jc1 = 1, jc2 = 1;

//计算i!
for(int j = 1; j <= i; j++){
jc1 *= j;
}
//计算i+1!
for(int j = 1; j <= i+1; j++){
jc2 *= j;
}

sum += 1.0 / (jc1+jc2);
}
cout << sum << endl;

return 0;
}

使用函数:
#include<iostream>

using namespace std;

//计算n的阶乘
double jc(int n){
double sum = 1;
for(int i = 1; i <= n; i++){
sum *= i;
}
return sum;
}

//计算1/1!--1/10!
int main()
{
double sum = 0;

for(int i = 1; i <= 10; i++){
sum += 1.0 / (jc(i)+jc(i+1));
}
cout << sum << endl;

return 0;
}



## 2.重载函数

#include<iostream>

using namespace std;

int Max(int a, int b){
return a > b ? a : b;
}

int Max(int a, int b, int c){
if(a >= b && a >= c){
return a;
}else if(b >= a && b >= c){
return b;
}else if(c >= a && c >= b){
return c;
}
}

int main()
{
cout << Max(1, 2) << endl;
cout << Max(1, 2, 3) << endl;

return 0;
}


2

3

## 3.值传递和地址传递

例三:
#include<iostream>

using namespace std;

void swap(int a, int a){
int temp;
temp = a;
a = b;
b = temp;
}

int main()
{
int x = 1, y = 2;
cout << "x = " << x << " y = " << y << endl;
swap(x, y);
cout << "x = " << x << " y = " << y << endl;

return 0;
}


x = 1 y = 2

x = 1 y = 2

例4：
#include<iostream>

using namespace std;

void swap(int &a, int &b){
int temp;
temp = a;
a = b;
b = temp;
}

int main()
{
int x = 1, y = 2;
cout << "x = " << x << " y = " << y << endl;
swap(x, y);
cout << "x = " << x << " y = " << y << endl;

return 0;
}


x = 1 y = 2

x = 2 y = 1

## 4.编写递归函数

例5:编写递归函数计算1+2+...+n
#include<iostream>

using namespace std;

int fc(int n){
if(n <= 1){
return 1;
}else{
return n+fc(n-1);
}
}

int main()
{
int n;
cin >> n;
cout << "ans = " << fc(n) << endl;

return 0;
}


例6:若f(1)=1,f(2)=2,f(n) = f(n-1)+f(n-2),求f(n)
#include<iostream>

using namespace std;

int f(int n){
if(n == 1){
return 1;
}else if(n == 2){
return 2;
}
else{
return f(n-1)+f(n-2);
}
}

int main()
{
int n;
cin >> n;
cout << "f(n) = " << f(n) << endl;

return 0;
}


posted @ 2019-09-14 20:11  美团骑手阿霖  阅读(229)  评论(2编辑  收藏  举报