加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

vb6 – Visual Basic 6.0中的自动类型转换

发布时间:2020-12-17 07:26:01 所属栏目:百科 来源:网络整理
导读:当我们在Visual Basic 6.0中将float转换为整数时,它如何使小数部分变圆?我正在谈论自动类型转换. 如果我们分配喜欢 Dim i as Integeri=5.5msgbox i 它会打印什么? 5或6 ?? 几个月前我得到了“5”.有一天它开始给我6个! 任何想法都错了吗?微软是否发布了
当我们在Visual Basic 6.0中将float转换为整数时,它如何使小数部分变圆?我正在谈论自动类型转换.

如果我们分配喜欢

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

解决方法

部分内容在VB6帮助中:主题类型转换函数.不幸的是,它是MSDN网站上 VB6 documentation以外的主题之一,但是如果你已经安装了VB6的帮助,它就会在那里.

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'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读