Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

pow

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 ?

like image 566
ango Avatar asked Oct 29 '11 06:10

ango


People also ask

Does POW return integer?

The pow() function takes 'double' as the arguments and returns a 'double' value. This function does not always work for integers.

What type of value is returned by POW?

The pow() function (power function) in C is used to find the value x y x^y xy (x raised to the power y) where x is the base and y is the exponent. Both x and y are variables of the type double. The value returned by pow() is of the type double.

Is POW function slow?

Without further optimizations from the compiler (like inlining or using built in functions for some special type of powers like integer exponent), pow is almost always much slower.


2 Answers

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.

like image 195
Marcelo Cantos Avatar answered Sep 28 '22 08:09

Marcelo Cantos


replace

val = (int)pow(5, i);

with

double d = pow(5,i);
val = (int)((d > 0.0) ? floor(d + 0.5) : ceil(d - 0.5));
like image 39
AndersK Avatar answered Sep 28 '22 08:09

AndersK