Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

A power function does't return a float

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading