Tas*_*sos 0 vb.net floating-point
我正在开发一个VB.Net项目.在解决方案的某个地方,我有这部分代码:
Dim my_variable As Single = 1
'other code goes here
If do_some_tests_here Then
my_variable = 0.9
End If
If my_variable < 0.9 Then
'do some other stuff here
End If
Run Code Online (Sandbox Code Playgroud)
我意识到当my_variable进入第一个If并将其值更改为时0.9,则第二个条件my_variable < 0.9返回True并执行内部代码.
我已经阅读了比较浮点数问题,你应该避免它,但是上面的替代解决方案是什么?
小智 7
如果将变量从Single更改为Double,则似乎不会出现此问题.我认为编译器本身将0.9变为双精度.但您也可以使用以下方法将0.9转换为单个:
If my_variable < CSng(0.9) Then
或者您可以通过使用字母F告诉编译器它是单一的(https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/data-types/type - 人物)
If my_variable < 0.9F Then
| 归档时间: |
|
| 查看次数: |
63 次 |
| 最近记录: |