i am using code block for learning c. my code is
#include
#include
int main()
{
int x;
x = pow(5,2);
printf(\"%d\", x);
}
Out
It seems that there is nothing wrong with the second program, except that you must add at the end
return 0;
If you read the value j with 2 then the result will be just 25.
I suspect you have a naive implementation of pow
in your libm
(I get 25, as it should be). If that computes pow(x,y)
as exp(y*log(x))
for positive x
without checking for (small) integral exponents and treating them specially, you get
Prelude> 2 * log 5
3.2188758248682006
Prelude> exp it
24.999999999999996
a double
result slightly smaller than 25, so when that is converted to int
it is truncated to 24.
To check, assign the result of pow(i,j)
to a double
and print that out.
With hardcoded pow(5,2)
, the compiler (most likely, it's what gcc does even without optimisation) computes the result during compilation exactly.
Try changing initialization to this:
int x=-1 ,i=-1 ,j=-1;
And last print to this:
printf("pow(%d, %d) == %d\n", i, j, x);
That should give good hint about the problem. Also, check return values of scanf
, they should return number of items read, ie. 1 with code above.
It's almost certain, that you entered invalid input for scanf, and i
or j
were left uninitialized, and that 24 is just garbage value.
Also, compile with warnings enabled, and fix them (like, add return 0;
to end of main
).
Using your code i got result 25 which is correct. Although Try changing the data type of result such as float or double.
Your code correctly gives 25 on my windows x64.
You probably needs to run it again see if you just read it wrong...
The missing "return 0;" is not the problem here.
If, anything, could ever go wrong,
you can try adding
fflush(stdin);//or out
after very scanf and printf. If any of the flushes solves your problem, you know what is going wrong.