我在EDIT中输入一串带空格的数字(例如:12 45 44 54 8 2)如何统计出数值的平均值(是指有空格隔开的数值和的平均值,数值的个数不确定是随意输入的)

解决方案 »

  1.   

    procedure StrToStrings(S, Sep: string;
      const List: TStrings);
    var
      I, L: Integer;
      Left: AnsiString;
    begin
      Assert(List <> nil);
      List.Clear;
      L := Length(Sep);
      I := Pos(Sep, S);
      while (I > 0) do
      begin
        Left := LeftStr(S, I - 1);
        List.Add(Left);
        Delete(S, 1, I + L - 1);
        I := Pos(Sep, S);
      end;
      if S <> '' then
        List.Add(S);
    end;
      

  2.   

    你可以将他存到一个string类型的变量里.随后使用pos做循环截取每个数值,转化相加求得平均值..........
      

  3.   

    var
      s: string;
      i, sum: Integer;
      strs: TStrings;s := "12 45 44 54 8 2";
    strs := TStringList.Create;
    StrToStrings(s, " ", strs);
    sum := 0;
    for i := 0 to strs.Count - 1 do
      sum := sum + StrToInt(strs[i]);
    Result := sum / strs.Count
      

  4.   

    var
        count,x,y,sum:integer;
        s:string;
    begin
        x:=0;
        count:=0;
        sum:=0;
        s:=Edit1.Text;
        while(length(trim(s))>0) do
        begin
            y:=pos(' ',s);
            if (y=0) then
            begin
                sum:=strtoint(s)+sum;
                count:=count+1;
                showmessage('平局数=   '+floattostr(sum/count) +' and sum= '+inttostr(sum));
                break;
            end
            else
            begin
                sum:=strtoint(trim(copy(s,1,y)))+sum;
                s:=copy(s,y+1,length(s)-y);
                count:=count+1;
            end;
            s:=trim(s);
        end