限制範圍的加法LimitPlus
引入: 自定義
如果我們希望讓兩數相加,又不希望超出某個範圍,若超出範圍則以該範圍計算,就使用自定義函式LimitPlus。
在這之前我們需要用到Visual Basic 沒有內建的數學函式Stick(m, n)。
]Function Stick(ByVal Main As Object, ByVal Target As Object)As Short
]If (Main - Target = 0) Then
]Return 0
]End If
]Return ((Main - Target) / ((Main - Target) ^ 2) ^ (1 / 2))
]End Function
LimitPlus 的用法是LimitPlus(主要數值, 增加數值, 限制數值),並且,此函式的解釋方式為,當主要數值小於限制數值的時候,求和不能大於限制數值,反之,當主要數值大於限制數值時,求和不能小於該限制數值。
]Function LimitPlus(ByVal Main As Long, ByVal Addition As Long, ByVal Limit As Long)As Long
]If (Stick(Main, Limit) * Stick(Main + Addition, Limit) <= 0) Then
]Return Limit
]End If
]Return Main + Addition
]End Function
]
]MsgBox(LimitPlus(1, 2, 3)) //1 + 2 = 3,此函式容許和與限制數值相等。MsgBox 裡顯示3。
]MsgBox(LimitPlus(1, 2, 1)) //主要數值1 已經在界線上了,傳回1。MsgBox 裡顯示1。
]MsgBox(LimitPlus(1, 2, 2)) //1 < 2,所以求和不能大於2。MsgBox 裡顯示2。
]MsgBox(LimitPlus(1, -2, 0)) //1 > 0,所以求和不能小於0。MsgBox 裡顯示0。
]MsgBox(LimitPlus(1, 2, 0)) //1 > 0,所以求和不能小於0。和為3,不小於0。MsgBox 裡顯示3。
