Function gets invalid values

so I have this function in C to calculate power and I use 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 this, I know, but it’s not him when I debug it, the values ​​are scanned correctly (that is, the values ​​are correct until the function is called), but then when entering the function a becomes 0 and n becomes 1074790400, and you can guess what will happen next ... the
first function is called from the main file, I included the full code, because I really don’t know what can happen, and I can’t even think about how to do this for Google ...
weird I wrote a function in a single file and it works fine, but it should definitely work in both directions.

any idea why this is happening?

+3
4

#include "power.h"

power.c?

, , get_power() , double float, , int float.

, .

+6

pow math.h. get_power, for.

0

- , ?

- ():

float get_power(float a, int n)
{
    float result = 1.0;
    for (int i = 0; i < n; i++)
    {
        result = result * a;
    }
    return result;
}
0

, xlc, , . :

"power.c", line 25.7: 1506-343 (S) Redeclaration of get_power differs from previous declaration on line 19 of "power.c".
"power.c", line 25.7: 1506-050 (I) Return type "float" in redeclaration is not compatible with the previous return type "int".
"power.c", line 25.7: 1506-379 (I) Prototype for function get_power must contain only promoted types if prototype and nonprototype declarations are mixed.
"power.c", line 25.7: 1506-380 (I) Parameter 1 has type "float" which promotes to "double".

I also tried this on several other compilers that I had, and got variations of this theme. You can see this as a warning in VS if you raise the warning level.

So, in conclusion, SHOULD NOT compile, and VS is the only one that compiles and links it.

0
source

Source: https://habr.com/ru/post/1784874/


All Articles