C language - recursive implementation of n to the kth power

  1. analyze

Here only n and k integer cases are discussed

Classification Discussion - Divide k into three cases

  • ①k>0

eg.2 to the 5th power - 2*2*2*2*2 is 2*2 to the 4th power

  • ②k=0

As long as n is not equal to 0, the result is 1

  • ③k<0

eg. 2 to the -5th power - 1 to 2 to the 5th power


  1. the code
#include<stdio.h>
double fun(int n, int k)
{
    if (0 == k&&n!=0) return 1;
    else if(0==k&&0==n) printf("此情况不存在\n");
    else if (k > 0) return n * fun(n, k - 1);//k
    else return 1.0/ fun(n, -k);
}
int main()
{
    int n = 0, k = 0;
    scanf("%d%d", &n, &k);
    printf("%lf\n", fun(n, k));
    return 0;
}

Guess you like

Origin blog.csdn.net/outdated_socks/article/details/129306926