2

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);

 }

enter image description here

MD XF
  • 7,860
  • 7
  • 40
  • 71

4 Answers4

5

pow() returns a double, the implicit conversion from double to int 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

c=lround(pow((5),(n)));

In this case, as long as pow() has an error of less than +-0.5 you will get the expected result.

user3528438
  • 2,737
  • 2
  • 23
  • 42
0

pow() takes double arguments and returns a double.

If you store the return value into an int and print that, you may not get the desired result.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    Given that a `double` can be expected to have ~53 bits of precision, and `int` typically only has 32 bits, the reason is not the conversion itself, but rather inaccuracy in the `pow()` algorithm. – EOF Feb 26 '16 at 17:55
0

If you need accurate results for big numbers, you should use a arbitrary precision math library like GMP. It's easy:

#include <stdio.h>
#include <math.h>
#include <gmp.h>

int main(void) {
    int n;
    mpz_t c;

    scanf("%d",&n);
    mpz_ui_pow_ui(c, 5, n);
    gmp_printf("%Zd\n", c);

    return 0;
}
Ctx
  • 18,090
  • 24
  • 36
  • 51
0

You can use the %f format specifier while commanding printf func.You should see your result accurately. In %d format specifier the value tends to the final answer eg. 5^2=24.9999999999 and hence the answer shown is 24.