Whenever I input a number in this program the program return a value which is 1 less than the actual result ... What is the problem here??
#include<stdio.h>
#include<math.h>
int main(void)
{
int a,b,c,n;
scanf("%d",&n);
c=pow((5),(n));
printf("%d",c);
}
pow()
takesdouble
arguments and returns adouble
.If you store the return value into an
int
and print that, you may not get the desired result.If you need accurate results for big numbers, you should use a arbitrary precision math library like GMP. It's easy:
pow()
returns adouble
, the implicit conversion fromdouble
toint
is "rounding towards zero".So it depends on the behavior of the
pow()
function.If it's perfect then no problem, the conversion is exact.
If not:
1) the result is slightly larger, then the conversion will round it down to the expected value.
2) if the result is slightly smaller, then the conversion will round down which is what you see.
solution:
Change the conversion to "round to nearest integer" by using rounding functions
In this case, as long as
pow()
has an error of less than +-0.5 you will get the expected result.