return value of pow() gets rounded down if assigne

2019-01-03 07:13发布

I am using the pow function in C and storing the return value in an integer type. see the code snippet below:

for (i = 0; i < 5; i++){
    val = (int)pow(5, i);
    printf("%d, ", val);
}

here i, and val are integers and the output is 1, 5, 24, 124, 624. I believe this is because a float 25 is treated as 24.99999... which gets rounded down to 24 on assignment to an integer.

How can I by pass this if I still need to store the return value in an int ?

标签: c pow
4条回答
不美不萌又怎样
2楼-- · 2019-01-03 07:38

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.

查看更多
别忘想泡老子
3楼-- · 2019-01-03 07:44

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;
}
查看更多
一夜七次
4楼-- · 2019-01-03 07:46

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.

查看更多
\"骚年 ilove
5楼-- · 2019-01-03 07:50

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));
查看更多
登录 后发表回答