子程序

子程序18 09 16


方法:数学递归


5! 分段函数解决
递归研究 第N次和第N-1次的关系 数学归纳法
f(x)=1 (x=0)
f(x)=x*f(x-1) (x>0)
1 1 2 3 5
规律:
  1.每两个数之和等于第三个数
    利用规律推导每一个数
  2.每一个数等于前两个数之和.第1和第2是1
  a[i]=a[i-1]+a[i-2];
  f(x)=1 (x=1 x=2)
  f(x)=f(x-1)+f(x-2) (x>=3)

子程序: 返回值 参数

输入n.累加从1到n.输出和 n s

思想:无全局变量  主程序不要干预太多的变量
方法一://有参有返回值

 1 #include<iostream>
 2 using namespace std;
 3 int f(int x){  //子程序接收主程序传来的n.但用x接收 
 4   int s=0;
 5   for(int i=1;i<=x;i++){
 6     s+=i;
 7   } 
 8   return s;
 9 }
10 int main(){
11 int n;
12 cin>>n;
13 cout<<f(n);//主程序将n传给子程序f 
14 return 0;
15 }

方法二://无参无返回值

 1 #include<iostream>
 2 using namespace std;
 3 int n,s=0;
 4 void work(){
 5   for(int i=1;i<=n;i++){
 6     s+=i;
 7   }
 8   return 0;
 9 }
10 int main(){
11 cin>>n;
12 work();
13 cour<<s;
14 return 0;
15 }
原文地址:https://www.cnblogs.com/Gzznnn/p/13813165.html