如果分配到一个整数战俘的返回值()被向下取整 [英] return value of pow() gets rounded down if assigned to an integer

查看:106
本文介绍了如果分配到一个整数战俘的返回值()被向下取整的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是用在C POW 功能和存储在一个整数类型的返回值。看到下面的code片断:

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

在这里 I VAL 是整数,输出为 1,5, 24,124,624
我相信这是因为浮动25是24.99999 ......这被四舍五入至24日分配给一个整数处理。

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.

如何通过传递这一点,如果我还需要返回的值存储在一个int?

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

推荐答案

铸造 INT 前添加0.5。如果你的系统的运动,你可以调用C99 ROUND()的功能,但我preFER,以避免它的可移植性原因。

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

这篇关于如果分配到一个整数战俘的返回值()被向下取整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆