如果我们分配喜欢
Dim i as Integer i=5.5 msgBox i
它会打印什么? 5或6 ??
几个月前我得到了“5”.有一天它开始给我6个!
任何想法都错了吗?微软是否发布了一些补丁来解决问题?
更新:5.5转换为6但8.5到8!
更新2:添加CInt没有任何区别. CInt(5.5)给出6,而Cint(8.5)得到8!有点喜欢的行为.我应该尝试像地板(x 0.49);
解决方法
When the fractional part is exactly 0.5,CInt and CLng always round it to the nearest even number. For example,0.5 rounds to 0,and 1.5 rounds to 2. CInt and CLng differ from the Fix and Int functions,which truncate,rather than round,the fractional part of a number. Also,Fix and Int always return a value of the same type as is passed in.
隐式类型强制 – a.k.a. “evil type coercion (PDF)” – 从浮点数到整数使用与CInt和CLng相同的舍入规则.在手册中的任何位置似乎都没有记录此行为.
如果你想在小数部分> = 0.5时向上舍入,而在其他情况下向下舍入,一个简单的方法就是
n = Int(x + 0.5)
在我的脑海中,这是Mike Spross的RoundNumber :)的简短版本,它取代了VB6 Round功能.
'Written off the top of my head,seems to work. Public Function RoundNumber(ByVal value As Double,Optional PlacesAfterDecimal As Integer = 0) As Double Dim nMultiplier As Long nMultiplier = 10 ^ PlacesAfterDecimal RoundNumber = Int(0.5 + value / nMultiplier) * CDbl(nMultiplier) End Function
样本输出:
Debug.Print RoundNumber(1.6) '2' Debug.Print RoundNumber(-4.8) '-5' Debug.Print RoundNumber(101.7) '102' Debug.Print RoundNumber(12.535,2) '12.54'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。