Given two numbers base and exponent, pow() function finds x raised to the power of y i.e. xy
double pow(double x, double y); x : floating point base value y : floating point power value
Working of pow() function with integers
The pow() function takes ‘double’ as the arguments and returns a ‘double’ value. This functions does not always work for integers. One such example is pow(5, 2). When assigned to an integer, it outputs 24 on some compilers and works fine for some other compilers. But pow(5, 2) without any assignment to an integer outputs 25.
- This is because 52 (i.e. 25) might be stored as 24.9999999 or 25.0000000001 because the return type is double. When assigned to int, 25.0000000001 becomes 25 but 24.9999999 will give output 24.
- To overcome this and output the accurate answer in integer format, we can add 0.5 to the result and typecast it to int e.g (int)(pow(5, 2)+0.5) will give the correct answer(25, in above example), irrespective of the compiler.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.