二分法猜价格

假设商品价格在0-999之间,输入一个正确的价格.

方法1:从1开始从上逐进,直到与正确的相等

方法2:二分法,每次选取中间值,直至正确的值.

说明:二分法本质上分治法的一种的方法.

'//程序用逐步法猜价格
'//假设价格都是整数,没有小数
Sub GP_Step()
Dim Price&, i&, Guess&, Step&
'   正确价格,变量,猜想值
Dim Min&, Max&
'   最小值,最大值
Min = 1: Max = 999
With Sheet1
Price = .Cells(3, 1)
For i = Min To Max
  Step = Step + 1
   Guess = i
   If Guess = Price Then Exit For
Next i
.Cells(2, 5) = Guess
.Cells(2, 4) = Step
End With
End Sub

'//程序用二分法猜价格
'//假设价格都是整数,没有小数
Sub GP_Binary()
Dim Price&, i&, Guess&, Step&
'   正确价格,变量,猜想值
Dim Min&, Max&, ex#
'   最小值,最大值,精度
ex = 0.1
Min = 1: Max = 999
With Sheet1
Price = .Cells(3, 1)
Guess = Round((Min + Max) / 2, 0)
Do
Step = Step + 1
If Guess > Price Then
   Max = Guess
ElseIf Guess < Price Then
   Min = Guess
End If
   Guess = Round((Min + Max) / 2, 0)
Loop Until Guess = Price
.Cells(5, 5) = Guess
.Cells(5, 4) = Step
End With
End Sub


 

你可能感兴趣的:(零基础学算法)