C語言程式設計 練習題參考答案 第五章 (2) 遞迴函式

來源:互聯網
上載者:User

 /*  5.10 編寫函數,求Fibonacci數列的第n項 */

#include "stdio.h"
int fibonacci(int  n);

void main()
{
   int n;
   printf("求Fibonacci數列的第n項,請輸入n\n");
   scanf("%d", &n);  /* VC6中n要小於 ? */
   printf("Fibonacci數列的第%d項為%d", n, fibonacci(n));
}

int fibonacci(int  n)
{
    if(n==1 || n==2)
      return 1;
    else
      return fibonacci(n-1) + fibonacci(n-2) ;

}

  /*  5.11 編寫函數,判斷一個整數是否是迴文數 palindrome  */

#include "stdio.h"
int palindrome(long  n);

void main()
{
   long n;
   printf("判斷一個整數是否是迴文數,請輸入n\n");
   scanf("%ld", &n);
   if(palindrome( n ))
      printf("%ld是迴文數",n);
   else
      printf("%ld不是迴文數",n);
}

int palindrome(long  n)
{
   int i,bit=0;
   int a[10];
   while(n!=0)
   {
     a[bit]=n%10;
     n=n/10;
     bit++;
   }
   for(i=0; i<bit/2; i++)
   {
    if(a[i]!=a[bit-1-i])
       return 0;
   }
   return 1;
}

 /*  5.12 編寫函數,求x的n次方,n為不小於0整數  n>=0

*/

#include "stdio.h"
double power(double  x, int  n);

void main()
{
   int n;
   double x;
   printf("求x的n次方,請輸入x和n,數字間以空格隔開\n");
   scanf("%lf%d", &x, &n);
   printf("%lf的%d次方為%lf", x, n, power(x, n) );
}

double power(double  x, int  n)
{
    if(n==0)
      return 1;
    else
      return (x * power(x, n-1));

}

 

/*  5.13 編寫一個函數,用遞迴方法求n階勒讓德多項式的值 */

#include "stdio.h"
#include "conio.h"
double P(double  x, int  n);
void main()
{
    double  x; int  n;
    printf("求n階勒讓德多項式,請輸入x和n\n");
    scanf("%lf%d",&x, &n);
    printf("結果為%lf", P(x, n)) ;
    getch();
}

double P(double  x, int  n)
{
    if(n==0)  return 1;
    if(n==1)  return x;
    if(n>1) return ((2*n-1)*x-P(x,n-1)-(n-1)*P(x,n-2))/n;

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.