一组数字,找出最接近指定数字的数字
原帖为http://www.autoitx.com/thread-43750-2-1.htmlLocal $vCZ = 55Local $aNum =
Local $rt = _GetApproachesNum($vCZ, $aNum)
MsgBox(0, @error, $rt)
Func _GetApproachesNum($vCZ, $aNum)
If Not IsArray($aNum) Or UBound($aNum, 0) > 1 Then Return SetError(1, 0, 0)
Local $i, $vC, $iMix, $vNeed
For $i = 0 To UBound($aNum) - 1
$vC = $aNum[$i] - $vCZ
If $vC > 0 And (Not $iMix Or $vC < $iMix) Then Dim $vNeed = $aNum[$i], $iMix = $vC
Next
If Not $vNeed Then Return SetError(2, 0, 0)
Return $vNeed
EndFunc ;==>_GetApproachesNum这里输出的是55以下最接近的数字66,但是现在有个新需求,就是想把以上最接近的数字34也输出来
因为a版给的函数就没看懂,不会自己修改,故来请教 试试Local $vCZ = 55
Local $aNum =
Local $rt = _GetApproachesNum($vCZ, $aNum)
MsgBox(0, @error, $rt)
Func _GetApproachesNum($vCZ, $aNum)
If Not IsArray($aNum) Or UBound($aNum, 0) > 1 Then Return SetError(1, 0, 0)
Local $i, $vC, $iMix, $vC2, $iMix2, $vNeed, $vNeed2
For $i = 0 To UBound($aNum) - 1
$vC = $aNum[$i] - $vCZ
$vC2 = $aNum[$i] - $vCZ
If $vC2 < 0 And (Not $iMix2 Or $vC2 > $iMix2) Then Dim $vNeed2 = $aNum[$i], $iMix2 = $vC2
If $vC > 0 And (Not $iMix Or $vC < $iMix) Then Dim $vNeed = $aNum[$i], $iMix = $vC
Next
If Not $vNeed Then Return SetError(2, 0, 0)
Return $vNeed2 & ' > [' & $vCZ & '] < ' & $vNeed
EndFunc ;==>_GetApproachesNum
正好有查找最接近数字的需求,MARK一下。 经过实测,函数有问题:
Global $fengli
$fengli = 71
$fengli = 0
$fengli = 0.1
$fengli = 0.7
$fengli = 1.1
$fengli = 1.3
$fengli = 1.8
$fengli = 2
$fengli = 2.3
$fengli = 2.4
$fengli = 2.8
$fengli = 3
$fengli = 3.5
$fengli = 3.6
$fengli = 4
$fengli = 4.2
$fengli = 4.6
$fengli = 4.8
$fengli = 5.2
$fengli = 5.4
$fengli = 5.8
$fengli = 6
$fengli = 6.4
$fengli = 6.5
$fengli = 7
$fengli = 7.2
$fengli = 7.5
$fengli = 7.8
$fengli = 8.2
$fengli = 8.4
$fengli = 8.8
$fengli = 8.8
$fengli = 9.3
$fengli = 9.5
$fengli = 9.8
$fengli = 10
$fengli = 10.6
$fengli = 10.6
$fengli = 11.2
$fengli = 11.2
$fengli = 11.7
$fengli = 11.7
$fengli = 12
$fengli = 12.2
$fengli = 12.7
$fengli = 12.8
$fengli = 13.2
$fengli = 13.5
$fengli = 13.8
$fengli = 14
$fengli = 14.2
$fengli = 14.5
$fengli = 14.8
$fengli = 15
$fengli = 15.5
$fengli = 15.5
$fengli = 16
$fengli = 16
$fengli = 16.5
$fengli = 16.5
$fengli = 17
$fengli = 17
$fengli = 17.5
$fengli = 17.5
$fengli = 18
$fengli = 18
$fengli = 18.5
$fengli = 18.5
$fengli = 19
$fengli = 19
$fengli = 19.5
$fengli = 20
Local $input = 14
Local $rt = _GetApproachesNum($input, $fengli)
MsgBox(0, @error, $rt)
Func _GetApproachesNum($input, $fengli)
If Not IsArray($fengli) Or UBound($fengli, 0) > 1 Then Return SetError(1, 0, 0)
Local $i, $vC, $iMix, $vNeed
For $i = 0 To UBound($fengli) - 1
$vC = $fengli[$i] - $input
If $vC > 0 And (Not $iMix Or $vC < $iMix) Then Dim $vNeed = $fengli[$i], $iMix = $vC
Next
If Not $vNeed Then Return SetError(2, 0, 0)
Return $vNeed
EndFunc ;==>_GetApproachesNum
返回值竟然是14.2,而不是14.
页:
[1]