function getting wrong values

Posted by frankie on Stack Overflow See other posts from Stack Overflow or by frankie
Published on 2011-01-12T01:40:53Z Indexed on 2011/01/12 1:53 UTC
Read the original article Hit count: 484

Filed under:
|

so i have this function in C to calculate a power, and i'm using visual c++ 2010

power.h

void power();  
float get_power(float a, int n);  

power.c

void power()
{
    float a, r;
    int n;
    printf("-POWER-\n");
    printf("The base: ");
    scanf("%f", &a);
    n = -1;
    while (n < 0)
    {
        printf("The power: ");
        scanf("%d", &n);
        if (n < 0)
        {
            printf("Power must be equal or larger than 0!\n");
        }
        else
        {
            r = get_power(a, n);
            printf("%.2f ^ %d = %.2f", a, n, r);
        }
    };
}

float get_power(float a, int n)
{
    if (n == 0)
    {
        return 1;
}
    return a * get_power(a, n-1);
}

not the best way to do it, i know, but that's not it
when i debug it the values are scanned correctly (that is, the values are correct until just before the function call) but then upon entering the function a becomes 0 and n becomes 1074790400, and you can guess what happens next...
the first function is being called from the main file, i included the full code because i really have no idea what could be going on, and i can't even think on how to google for it...
strangely, i wrote the function in a single file and it works fine, but it definitely should work both ways

any idea why this is happening?

© Stack Overflow or respective owner

Related posts about c

    Related posts about visual-studio-2010