使用遞迴函式生成x的n次冪的C程式
問題
計算xn的值,其中x和n都是使用者在執行時提供的輸入。
解決方案
使用C語言中的遞迴函式生成x的n次冪值的解決方案如下:
查詢xn的邏輯如下:
//Calling function: Xpow=power(x,n); //Called function: if (n==1) return(x); else if ( n%2 == 0) return (pow(power(x,n/2),2)); /*if n is even*/ else return (x*power(x, n-1));
演算法
請參考以下演算法,使用遞迴函式生成x的n次冪的值。
步驟1 - 讀取長整型變數
步驟2 - 宣告函式原型
步驟3 - 呼叫函式
Xpown=power(x,n) goto step 5
步驟4 - 列印xpown
步驟5 - 被呼叫函式
步驟5.1 - if (n==1)
步驟5.1.1 - return(x)
步驟5.2 - Else if (n%2 == 0)
步驟5.2.1 - Return (pow(power(x,n/2),2)); /*如果n是偶數*/
步驟5.3 - Else
步驟5.3.1 - Return (x*power (x, n-1)); /*如果n是奇數*/
程式
以下是使用遞迴函式**生成x的n次冪值的C程式**:
#include <stdio.h> #include <math.h> void main(){ long int x, n, xpown; long int power(int x, int n); printf("Enter the values of X and N:
"); scanf("%ld %ld", &x, &n); xpown = power (x, n); printf("X to the power N = %ld
",xpown); } /*Recursive function to computer the X to power N*/ long int power(int x, int n){ if (n==1) return(x); else if ( n%2 == 0) return (pow(power(x,n/2),2)); /*if n is even*/ else return (x*power(x, n-1)); /* if n is odd*/ }
輸出
執行上述程式時,會產生以下結果:
Enter the values of X and N: 5 4 X to the power N = 625
廣告