我写了一个函数,比较粗糙,你看一看:
function GetData(x1,x2,usernum,x:integer):integer;
var
  x0,x4:integer;
begin
  i:=i+1;
  x0:=(x2-x1) div 2;
  x4:=x0+x;
  if (x4=usernum) then
     result:=x4
  else
  begin
     if x4>usernum then
        x4:=GetData(x1,x4,usernum,0);
     if x4<usernum then
        x4:=GetData(x4,x2,usernum,x4)
  end;        
  result:=x4;
end;
其中x1,x2表示猜的范围,在你的例子中是1,100000;
usernum是用户出的数字,如100,可由文本框接收;
x你在调用该函数的时候设置为0;
该函数返回计算机猜的数。
调用实例如下:
Edit2.Text:=IntToStr(GetData(1,100000,StrToInt(Form1.Edit1.Text),0));
Edit3.Text:='计算机猜了'+IntToStr(i)+'次';
i:=0;
该函数好像并不聪明,猜的次数也不算太少,请各位给与优化!

解决方案 »

  1.   

    从1到100000中确定用户的给定数字X,
    需要的信息量是I(x)=-log2(1/100000)=log2(100000)=5*3.3=16.6bit
    所以至少要作17次判断。
    算法:设猜数范围为W个数字,
    次数C:=Round(log(W)/log(2));
      

  2.   

    取对数的函数不记得了,抱歉。
    这里约定log(x)是取以10为底数的对数。
    C的求法就是将log2(W)舍入取整。
      

  3.   

    我已经自己求到了这个函数了。请大家到EXCEL 97或2000中的VBA编辑器加入一个模块,再粘贴下面代码,再运行gostart,在立即窗口中就看到答案了。
    也谢谢gz_xjf(thinker) 给我的提示,谢谢大家。
    Option Explicit
    Dim x As Integer
    Dim i As IntegerFunction f(a As Integer, b As Integer) As Integer
      Dim c As Integer
      
      i = i + 1
      If a = x Then f = a: Exit Function
      If b = x Then f = b: Exit Function
      
      c = Int((b - a) / 2) + a
      If c = a Then c = c + 1
      
      If c = x Then
        f = c
      ElseIf x > c Then
        f = f(c + 1, b)
      ElseIf x < c Then
        f = f(a, c - 1)
      End IfEnd FunctionSub gostart()
      i = 0
      x = 1047
      Debug.Print f(1, 10000)
      Debug.Print i
      
    End Sub
      

  4.   

    呵,原来仔看之下可以更简的:
    Option Explicit
    Dim x As Integer
    Dim i As IntegerFunction f(a As Integer, b As Integer) As Integer
      Dim C As Integer
      
      i = i + 1
      C = (b - a) / 2 + a
      If C = x Then
        f = C
      ElseIf x > C Then
        f = f(C + 1, b)
      ElseIf x < C Then
        f = f(a, C - 1)
      End IfEnd FunctionSub gostart()
      i = 0
      x = 1047
      Debug.Print f(1, 10000)
      Debug.Print i
      
    End Sub