return value of pow() gets rounded down if assigned to an integer

穿精又带淫゛_ 提交于 2019-11-26 12:33:14
Marcelo Cantos

Add 0.5 before casting to int. If your system supports it, you can call the C99 round() function, but I prefer to avoid it for portability reasons.

replace

val = (int)pow(5, i);

with

double d = pow(5,i);
val = (int)((d > 0.0) ? floor(d + 0.5) : ceil(d - 0.5));

Implement pow yourself.

int myPow(int base, int exponent) {
    int n = 1;
    for (int i = 0; i < exponent; i++) {
        n *= base;
    }
    return n;
}

This, of course, only handles positive exponents, and only works on ints, and there are certainly more efficient ways to do it. See, for example, the source for ^ in Haskell.

Benas

I had this problem my self. I solved it easily in your instruction simply just add if statement.

if (k%n>0)
{
    k=k+1;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!