将变量强制转换为int vs round()函数 [英] cast variable to int vs round() function

查看:130
本文介绍了将变量强制转换为int vs round()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在(int)someValue不准确的几个地方看到了它,而是出现了round()函数所要求的问题.两者有什么区别?

I have seen it in several places where (int)someValue has been inaccurate and instead the problem called for the round() function. What is the difference between the two?

具体来说,如果需要的话,对于C99C.使用Java编写程序时,我在程序中也遇到了相同的问题.

Specifically, if need be, for C99 C. I have also seen the same issue in my programs when writing them in java.

推荐答案

在将float/double值强制转换为int的情况下,通常会由于以下原因而松开 fractional 部分: 整数截断.

In case of casting a float/double value to int, you generally loose the fractional part due to integer truncation.

这与我们通常期望的舍入有很大不同,例如2.8以整数截断最终以2结束,就像2.1最终以2结束一样.

This is quite different from rounding as we would usually expect, so for instance 2.8 ends up as 2 with integer truncation, just as 2.1 would end up as 2.

更新:

铸造的另一个潜在(粗略)不准确性的原因是,相对于浮点类型,可以使用整数表示值的范围有限(感谢@R在下面的评论中提醒我们这一点)

Another source of potential (gross) inaccuracy with casting is due to the limited range of values being able to be represented with integers as opposed to with floating point types (thanks to @R reminding us about this in the comment below)

这篇关于将变量强制转换为int vs round()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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