C 程序计算 x^n - 计算 pow(x,n) 的程序


2023 年 1 月 8 日, Learn eTutorial
3046

在这个 C 程序中,我们需要计算 'xn 次方',其中 'x' 和 'n' 由用户给出。为此,我们使用递归函数 pow(x,n)。例如,如果 'x' 等于 2,'n' 是 3,那么结果将是 8。在这个函数中,我们分别进行计算,对于偶数返回 "(pow(pow(x,n/2),2));",对于奇数返回 "(x*pow(x, n-1))"。

什么是递归函数?

递归函数是调用自身的函数,直到满足退出条件。因此,同一个函数会多次调用自身。

什么是 pow() 函数?

函数 pow() 用于计算一个数的幂,定义在数学库中。pow() 函数的语法如下所示。

double pow(double a double b) 

  • pow() 计算数字 'a' 的 'b' 次方。其中 'a' 和 'b' 是用户输入。

算法

步骤 1: 包含头文件,以便使用 C 中内置的函数。

步骤 2: 将变量 'x, n, xpown' 声明为 长整型

步骤 3: 声明函数 long int pow(int x, int n)

步骤 4: 从用户处读取 XN 的值。

步骤 5: 调用函数 xpown = pow (x,n)

步骤 6: 显示 XN 次方是 xpown


函数 long int pow(int x, int n)

步骤 1: 检查 n==1,如果为真则 return(x)

步骤 2: 否则检查 n%2 == 0,如果为真则返回 (pow(pow(x,n/2),2)),否则执行步骤 3。

步骤 3: 返回 (x*pow(x, n-1))。


为了找到一个数的幂,我们在 C 中使用了以下概念。我们建议参考这些概念以获得更好的理解

C 语言源代码

                                          #include <stdio>
#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"); /* accepts the user input */
  scanf("%ld %ld", & x, & n);
  xpown = power(x, n);
  printf("X to the power N = %ld\n");
}
/*Recursive function to compute 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)); /*use this when the n i even*/
  else
    return (x * power(x, n - 1)); /* if n is odd*/
}
                                      

输出

Enter the values of X and N
2 5
X to the power N = 32

RUN2

Enter the values offX and N
4 4
X to the power N ==256

RUN3

Enter the values of X and N
5 2
X to the power N = 25

RUN4

Enter the values of X and N
10 5
X to the power N = 100000