当容差以 ±2 等格式提供时,如何评估整数或小数是否在容差范围内?



我有一个公差表,可以应用于应用程序中的值。

公差的格式为 ±2、±1、-2/+1 例如,有许多组合,但所有组合要么加/减相同的值,要么加一个值减去不同的值。

我想知道如何评估天气值在公差范围内。

例如,值为 100,公差为 ±2,我知道该值必须在 98 到 102 之间。

我想避免像这样编写 if 语句:

If toleranceID = 1 Then '±2
If value < 98 OrElse value > 102 Then
'Fail
End If
ElseIf toleranceID = 2 Then '±1
If value < 99 OrElse value > 101 Then
'Fail
End If
ElseIf toleranceID = 3 Then '-2/+1
If value < 98 OrElse value > 101 Then
'Fail
End If
End If

因为有很多不同的公差。

编辑:我不觉得这个问题太宽泛了?

我只是问是否有办法做到这一点,而不必写一个大的If Else If语句。请您提供我需要添加哪些信息,或者应该关闭它的原因。如果原因足够公平,我很乐意关闭它。

只是一个示例,我尝试使用字典:

Dim Tolerance As New Dictionary(Of String, String)
Private Sub FrmTest_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Tolerance.Add("+2-1", "-1, 2") '(Tolerance key, tolerance value)
Tolerance.Add("+1-1", "-1, 1")
Tolerance.Add("+1-2", "-2, 1")
MsgBox(CheckTolerance(100, 99, "+2-1"))
End Sub
Private Function CheckTolerance(RefVal As Integer, CheckVal As Integer, UsedTolerance As String) As Boolean
Dim HighTol As Integer = 0
Dim LowTol As Integer = 0
If Not Tolerance.ContainsKey(UsedTolerance) Then
MsgBox("Your Tolerance Is Invalid")
Return False
End If
Integer.TryParse((Tolerance(UsedTolerance).ToString.Split(",".ToCharArray))(0), LowTol)
Integer.TryParse((Tolerance(UsedTolerance).ToString.Split(",".ToCharArray))(1), HighTol)
If CheckVal >= (RefVal + LowTol) And CheckVal <= (RefVal + HighTol) Then
Return True
Else
Return False
End If
End Function

将值加载到字典结构中,并创建一个如下所示的函数(伪代码(

函数 IsWithinTolerance (value, toleranceKey( 布尔值

从字典中获取宽容 容差将解析该值并返回 +/- 值 变量容差 = 获取容差(键(

返回(值 <= 容差.最大值 和值>= 公差.minValue(

结束功能

最新更新