I have got a question from my junior and I can't fix it. Following is the code he is using in the Code::Blocks IDE just downloaded from official site of Code::Blocks.
It's a hello world console project, which he just modified a little, using the header file math.h and using pow() function.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
printf("Hello world! %d\n",pow(2,2));
return 0;
}
The output of this code should be Hello world! 4 right? But voila it's always Hello world! 0 unless I use printf("Hello world! %f\n", pow(2,2)); which is syntactically, yeah perfect and the right thing to do. But then it's another story altogether.
Pow function should return 4, double, of course. So what is happening? printf() is not working correctly, or there is some issue with pow().
The return value of pow() is double as you can see here:
http://www.tutorialspoint.com/c_standard_library/c_function_pow.htm
So you have to cast the return value to int like this:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
printf("Hello world! %d\n",(int)pow(2,2));
return 0;
}
Otherwise as you saw is the output 0!
Another example to show this you can try this:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
printf("Hello world! %d\n",4.000000);
return 0;
}
As you will see the output is also 0 because it's a double value!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With