第二次作业

教案

一、为什么要用函数

1、函数主要是面向对象,为每一项代码功能,实现清晰的操作
2、实现代码复用,功能的修改
例:

  1. #include<iostream>
  2. using namespace std;
  3. int add(int n,int m)
  4. {
  5. int reason;
  6. reason = n + m;
  7. return reason;
  8. }
  9. int main()
  10. {
  11. int n,m;
  12. cout <<" Please enter your number "<< endl;
  13. cin >> n>>m;
  14. cout << "The reason is " << add(n, m)<< endl;
  15. }

通过调用函数add进行加法操作,若想让程序改为减法功能,只用修改add函数。

二、为什么要用函数重载

1、函数重载不需要因为函数的细微功能而建立太多函数。
2、多个函数用同一个名字,调用的时候,根据参数类型可以自动调用对应的函数。从而减少了代码工作量。
例:

  1. #include <iostream>
  2. using namespace std;
  3. void say_hello(void)
  4. {
  5. cout << "this is hello" << endl;
  6. }
  7. void say_hello(int a = 100)
  8. {
  9. cout << "this is hotdog" << endl;
  10. }
  11. void say_hello(double a)
  12. {
  13. cout << "this is hotpig:" << a << endl;
  14. }
  15. //参数个数不同的重载
  16. void say_hello(int a, int b, int c)
  17. {
  18. cout << "a+b+c = " << a + b + c << endl;
  19. }
  20. int main(void)
  21. {
  22. say_hello(100);
  23. say_hello(11.11);
  24. say_hello(1, 2, 3);
  25. }

通过相同的函数名称,调用不同参数的值,可以减轻程序员的工作量。

三、什么是值传递

1、值传递是单项的,参数的值只能传入,不能传出,当函数内部需要修改参数,并且不希望这个改变影响调用者时,采用值传递。
2、设计实验:传值通过一个函数,对其数据进行修改再返回,与直接输出形成对比。
例:

  1. #include <iostream>
  2. using namespace std;
  3. int Fun1(int a)
  4. {
  5. a = a + 1;
  6. return a;
  7. }
  8. int main()
  9. {
  10. int a = 1;
  11. cout << Fun1(a) << endl;
  12. cout << a << endl;
  13. return 0;
  14. }

由上述所述,通过函数的值返回值为2,未通过函数的值返回值为1。

四、什么是地址传递

1、地址传递与值传递不同,地址传参传递的是存放这个变量内存的地址。
2、设计实验:与上题类似,但将传值改为传地址。

  1. int Fun1(int* a)
  2. {
  3. *a = *a + 1;
  4. return *a;
  5. }
  6. int main()
  7. {
  8. int a = 1;
  9. cout<<Fun1(&a)<<endl;
  10. cout<<a<<endl;
  11. return 0;
  12. }

执行出来的结果都为2,由此可以看来地址传参可以改变原来参数的值。

五、如何编写递归函数

1、递归函数是一种反复调用自身的函数,是把问题转化为规模缩小了的同类子问题,然后递归调用函数来表示问题的解,必须拥有终止结果,效率低。
2、例子:菲波拉契数列

  1. #include <iostream>
  2. #include<iomanip>
  3. using namespace std;
  4. int Fib(int x);
  5. int main()
  6. {
  7. int n;
  8. int x;
  9. cout << "enter the number you want:";
  10. cin >> n;
  11. x = Fib(n);
  12. cout << "Fib(" << n << ")=" << x << endl;
  13. }
  14. int Fib(int x)
  15. {
  16. if (x == 1 || x == 2)
  17. return 1;
  18. else
  19. return Fib(x - 1) + Fib(x - 2);
  20. }

若输出x为5,反复调用Fib函数,得出斐波拉契数列为5。

posted @ 2019-09-14 22:12  R丶f  阅读(154)  评论(0编辑  收藏  举报