9.9 使用递归函数重写编程练习8

#include <stdio.h>
double power(double n, int p);
int main(void)
{
    double x, xpow;
    int exp;

    printf("Enter a number and the positive integer power");
    printf(" to which\nthe number will be raised. Enter q");
    printf(" to quit.\n");
    while (scanf("%lf%d", &x, &exp) == 2)
    {
        xpow = power(x,exp);
        printf("%.3g to the power %d is %.5g\n", x, exp, xpow);
        printf("Enter next pair of numbers or q to quit.\n");
    }
    printf("Hope you enjoyed this power trip -- bye!\n");

    return 0;
}

double power(double n, int p)
{
    double pow = 1;
    int i;

    if (p == 0 )
    {
        if (n ==0)
        {
            printf("the 0^0 is not define and as the value is 1\n");
                pow = 1;
        }
        else
            pow = 1;
    }

    else
    {
       if (p == 1)
        pow = n;
       else
       {
        pow = power(n,p-1)*n;
       }
    }

    return pow;
}

猜你喜欢

转载自blog.csdn.net/qq_36324796/article/details/78993638
9.9