使用递归函数生成 x 次方 n 的值的 C 程序

问题

计算 x n的值,其中 x 和 n 都是用户在运行时给出的输入

解决方案

使用 C 语言中的递归函数生成 x 幂 n 的值的解决方案如下 -

下面提到了找到 x n的逻辑-

//调用函数:
Xpow=power(x,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));

算法

参考下面给出的算法,使用递归函数生成 x 幂 n 的值。

步骤 1 - 读取 long int 变量

第 2 步- 声明函数原型

步骤 3 - 调用函数

Xpown=power(x,n) goto step 5

第 4 步- 打印 xpown

步骤 5 - 调用函数

   步骤 5.1 - 如果 (n==1)

      步骤 5.1.1 -return(x)

   步骤 5.2 - 否则如果 (n%2 == 0)

      步骤 5.2.1 - 返回 (pow(power(x,n/2),2)); /*如果n是偶数*/

   步骤 5.3 - 其他

      步骤 5.3.1 - 返回 (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: \n");
   scanf("%ld %ld", &x, &n);
   xpown = power (x, n);
   printf("X to the power N = %ld\n",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