this one prints 100:
int j=2;
int i= pow(10,2);
printf("%d\n", i);
and this one prints 99:
int j=2;
int i= pow(10,j);
printf("%d\n", i);
why?
this one prints 100:
int j=2;
int i= pow(10,2);
printf("%d\n", i);
and this one prints 99:
int j=2;
int i= pow(10,j);
printf("%d\n", i);
why?
What's going on is that you have a C implementation whose standard library has a very low quality implementation of
pow
which is returning inexact results even when the exact result is representable in the type (double
). The call topow(10,2)
seems to producing the value just below100.0
, which, when rounded to an integer, yields 99. The reason you don't see this when the arguments are constant is that the compiler took the liberty to optimize out the call alltogether and replace it with a constant 100 at compiletime.If your intent is to do integer powers, don't use the
pow
function. Write a proper integer power function, or when the exponent is known, just write out the multiplication directly.pow
returnsdouble
and so if the result is not exactly100
but slightly less than it will truncate when converting to anint
and you will receive the99
result you are seeing. It would be interesting to see what the results look like for adouble
variable and%f
format.The reason you won't see it when you use literals is because of constant folding which will cause the call to
pow
to be optimized out and replaced with a constant. We can see the version that uses constants when we generate the assembly no call topow
is made it just moves the end result100
(see it live):while the version the second version actually calls
pow
(see it live):In the first case, I suspect the compiler has optimized the value to
10*10
without actually callingpow
(compilers do actually do this). In the second case, it looks like you have a floating-point rounding error. The result is almost 100 but not quite, and the implicit cast toint
truncates it.The
pow
function operates ondouble
, notint
.In general (but not always), when you convert doubles to integers, you call
round()
. Eg:If your C library doesn't have this, you can emulate: