首页 > 解决方案 > 在 vb.net 中除以两倍是错误的

问题描述

我在我的程序 vb.net 中使用这个函数

Public Function getmeter(ByVal metersize As Double) As Double
        Dim result As Double
        Dim remain As Double = metersize / size
        SplitDouble(remain)
        result = Calcuatedemeter(cartons, plateNum)

        Return result
    End Function

虽然我给出了这个值,metersize =1365.28 size=1.61 结果应该是 848 我在我的计算器和谷歌计算器和duckduckgo计算器的 sci-calculator 中测试它,但在 vb.net 中它告诉我 847.999999 为什么会这样。

这个计算器

 Private Function Calcuatedemeter(ByVal cartonnumber As Integer, ByVal platenumber As Integer) As String
        Dim result As String = ""
        Dim sb As New System.Text.StringBuilder()
        If cartonnumber > 0 Then
            sb.Append(cartonnumber)
            sb.Append(" Carton  ")
        End If
        If Not platenumber = 0 And cartonnumber > 0 Then
            sb.Append(" و  ")
        End If

        If platenumber > 0 Then
            sb.Append(" " & platenumber & " Peace ")
        End If
        result = sb.ToString

        Return result
    End Function

我正在使用这个函数从数据库中获取值

Function getInfoceramic(ByVal gsize As Double, ByVal gcarton As Integer, ByVal gname As String, ByVal gwidth As Double, ByVal glength As Double) As Double
    size = CDbl(gsize)
    cartonpak = gcarton
    name = gname
    width = gwidth
    length = glength
    platesize = (width / 100) * (length / 100)


End Function

标签: vb.netalgorithm

解决方案


这是由于双精度值的性质,它们不存储为精确值,而是存储为非精确近似值。

这很好理解并且错误相关(参见:https ://en.wikipedia.org/wiki/Machine_epsilon )

如果您知道您只处理 2 个小数位,则可以使用整数并将其乘以 100 存储,然后仅在您想要输出值时除以 100。


推荐阅读