return value of pow() gets rounded down if assigned to an integer

c pow
ango picture ango · Oct 29, 2011 · Viewed 7.1k times · Source

I am using the pow function in C and storing the return value in an integer type. see the code snippet below:

for (i = 0; i < 5; i++){
    val = (int)pow(5, i);
    printf("%d, ", val);
}

here i, and val are integers and the output is 1, 5, 24, 124, 624. I believe this is because a float 25 is treated as 24.99999... which gets rounded down to 24 on assignment to an integer.

How can I by pass this if I still need to store the return value in an int ?

Answer

Marcelo Cantos picture Marcelo Cantos · Oct 29, 2011

Add 0.5 before casting to int. If your system supports it, you can call the C99 round() function, but I prefer to avoid it for portability reasons.