Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function getting wrong values

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?

like image 706
frankie Avatar asked Nov 19 '25 22:11

frankie


1 Answers

Do you have

#include "power.h"

at the top of power.c?

If not, the compiler doesn't know what the prototype of get_power() is at the point of the call, so it will resort to promoting the first argument to a double instead of passing it as a float. It'll also incorrectly assume that the result is an int instead of the float that's being returned.

If the compiler sees the prototype before the call, things will work better.

like image 182
Michael Burr Avatar answered Nov 21 '25 13:11

Michael Burr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!