遞歸邏輯——PTA習題為例


前言

PTA上的基礎函數題第10章全是用遞歸求解題目,非常好的學習資料,找個機會歸納一下,加強對遞歸的理解。

正文

練習10-1 使用遞歸函數計算1到n之和

本題要求實現一個用遞歸計算1+2+3+…+n的和的簡單函數。
函數接口定義:int sum( int n );

int sum( int n ){
     int re=0;
     if(n<0)//結束條件
       re=0;
	 else if(n){
        re=sum(n-1)+n;//回歸時的算式
	 }
	return re;//遞回
}

習題10-2 遞歸求階乘和

本題要求實現一個計算非負整數階乘的簡單函數,並利用該函數求 1!+2!+3!+...+n! 的值。

函數接口定義: double fact( int n ); double factsum( int n );

double fact( int n ){
	double sum;
	    if(n<=1)//結束條件
	       sum=1;
		else
		   sum=fact(n-1)*n;//求n的階層
        return sum;
} 
double factsum( int n ){/*求和*/
	double sum;
    if(n==0)//結束條件
      sum=0;
    else
      sum=factsum(n-1)+fact(n); //和上一題的求和相似,n變成n!,所以用相應的求階層函數fact(n)!
    return sum;
    
}

習題10-3 遞歸實現指數函數

本題要求實現一個計算x​^n(n≥1)的函數。
函數接口定義: double calc_pow( double x, int n );

double calc_pow( double x, int n ){
	double sum;
	if(n==0)//結束條件
	  sum=1;
   /* else if(n==1)
      sum=x;*/
    else{
    	sum=calc_pow(x,n-1)*x;	//回歸過程
	}
	  return sum;
}

在這里插入圖片描述

習題10-4 遞歸求簡單交錯冪級數的部分和

本題要求實現一個函數,計算下列簡單交錯冪級數的部分和:

f(x,n)=x−x2+x3 −x4 +⋯+(−1)n−1 xn ​​

函數接口定義: double fn( double x, int n );

#double fn( double x, int n )
{
	int i;
	double f=1.0;
	/*求階層*/
	for(i=1;i<=n;i++)
			f=f*x;
	/*改變符號*/
	if(n%2==0)
	    f=f*(-1);
	/*遞歸*/
	if(n==1)//結束條件
		return x;
	else return (f+fn(x,n-1));//參看第一和第二題		
}

習題10-7 十進制轉換二進制

本題要求實現一個函數,將正整數n轉換為二進制后輸出。

函數接口定義: void dectobin( int n );

void dectobin( int n ){
	int re;
	if(n==0)
	  printf("0");
    else if(n==1)
      printf("1");
    else{
    	dectobin(n/2);
    	re=n%2;
	    printf("%d",re);
	}
}

在這里插入圖片描述

習題10-8 遞歸實現順序輸出整數

本題要求實現一個函數,對一個整數進行按位順序輸出。
函數接口定義: void printdigits( int n );

void printdigits( int n ){
	int re;
	if(n<=9)//結束條件,限制n為個位數
	  printf("%d\n",n); 
    else{
    	printdigits(n/10);
    	re=n%10;
    	printf("%d\n",re);
	}
}

再來看下這張圖
房間里的就是你編寫的遞歸體,是不是更清楚了呢
在這里插入圖片描述
遞歸並不像我想的那種順序進行代碼的運算 n先是減小到遞歸出口,就是像棧,先壓入后彈出,后壓入先彈出!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM