Power function returns 1 less result

喜你入骨 提交于 2019-12-02 04:52:28

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.

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.

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;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!