Some trouble with recursive Function

Viewed 83

I tried to use recursive function to create my power function.The Problem was given as:"Write a Power function, which can work with a base(natural) and a power(integer)". But there is a trouble when user "give me" negative power. Please find a mistake. All printf functions aren't needed(except printf's in main).

#include <stdio.h>

int Power(int power, float base)
{
    printf("%f\n", base);
    printf("POWER%d\n", power);
    if (power == 0)
    {
        return 1;
    }
    else
    {
        if (power < 0)
        {
            return Power(power *= -1, 1 / base);
        }
        else
        {
            if (power == 1)
            {
                printf("%f\n", base);
                // printf("POWER%d\n",power);
                return base;
            }
            else
            { //printf("%f\n",base);
                //printf("POWER%d\n",power);
                return base * Power(power - 1, base);
            }
        }
    }
}
int main()
{
    int a; //power
    printf("Enter a power: ");
    scanf("%d", &a);
    printf("Enter a base: ");
    float b; //base
    scanf("%f", &b);
    if (b == 0)
        printf("0");
    else
    {
        float y = Power(a, b);
        printf("%f", y);
    }
}
1 Answers

Try this in negative:

if (power<0)
        {
            return 1/Power(-power, base);
        }
Related