我的问题是;通过 roundedInt = (int)unRoundedDouble 和 roundedInt = (int)(floor(unRoundedDouble)) 将 double 向下舍入为 int 之间有功能差异吗?
我在代码中看到了后者的使用,并认为这可能是出于安全或功能原因,但无法弄清楚会以不同的方式处理什么。
此外:四舍五入的 Double 不会太大而无法放入 int,这是预先确定的。
最佳答案
它们本质上是不同的。转换为 int
会将非整数部分截断为 0
。 floor
也会做同样的事情,但是朝向-无穷大。
示例:
double d = -1.234;
printf("%d %d\n", (int)d, (int)floor(d));
产量:
-1 -2
关于C:将 double 向下舍入为 int 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28085955/