Pow () return value is rounded if an integer is assigned

I use the pow function in C and store the return value in an integer type. see 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 result is 1, 5, 24, 124, 624 . I believe this is due to the fact that float 25 is treated as 24.99999 ... which is rounded to 24 when assigned to an integer.

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

+6
c pow
Oct 29 '11 at 6:02
source share
4 answers

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

+9
Oct 29 2018-11-11T00:
source share
— -

replace

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

from

 double d = pow(5,i); val = (int)((d > 0.0) ? floor(d + 0.5) : ceil(d - 0.5)); 
+5
Oct 29 '11 at 7:10
source share

Introduce yourself.

 int myPow(int base, int exponent) { int n = 1; for (int i = 0; i < exponent; i++) { n *= base; } return n; } 

This, of course, only processes positive metrics and works only with ints, and there are, of course, more efficient ways to do this. For example, source ^ in Haskell .

+3
Oct 29 '11 at 6:13
source share

I had this problem. I easily decided in my instructions to simply add an if statement.

 if (k%n>0) { k=k+1; } 
-3
Nov 23 '13 at 20:40
source share



All Articles