Home > Back-end >  A power function does't return a float
A power function does't return a float

Time:01-27

I've made a program to find a power of any number. It sort of works but my problem is that it doesn't return float as it should

float power(float num, int pwr)
{
    float idx;
    float val;

    val = 1;
    idx = 0.00;

    while (idx < pwr)
    {
        val *= num;
        idx  ;
        printf("%f\n", val); 
    }

    return val;
}

int main(void)
{
    printf("%2.f\n", power(1.03, 5));
    return 0;
}

The result I get is this ;

$ gcc power.c && ./a.out
1.030000
1.060900
1.092727
1.125509
1.159274
 1

CodePudding user response:

Your function is returning a float and a float is being printed. The format specifier %2.f is telling it to not print any digits after the decimal point.

You may have instead wanted %.2f which will print 2 decimal places.

  •  Tags:  
  • Related