0

我正在尝试编写代码来计算来自形成 stringgrid 主对角线的单元格的所有数字的总和,但我得到的结果只是我在右下角单元格中输入的数字。这是我的代码:

procedure TForm1.Button1Click(Sender: TObject);
var
  i, j: Integer;
begin
  with StringGrid1 do
  begin
    RowCount := StrToInt(Edit1.Text);
    ColCount := StrtoInt(Edit2.Text);
    for i := 0 to RowCount - 1 do
      Cells[0, i] := IntToStr(i);
    for j := 0 to ColCount - 1 do
      Cells[j, 0] := IntToStr(j);
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  i, j, s, z, n: Integer;
begin
  z := 0;
  with StringGrid1 do
  begin
    for i := 1 to RowCount - 1 do
      for j := 1 to ColCount - 1 do
        s := StrToInt(Cells[j, i]);

    for n := RowCount - 1 to ColCount - 1 do
      if i = j then
        z := z + s;

    Label1.Caption := IntToStr(z);
  end;
end;

end.

我错过了什么?提前致谢

4

1 回答 1

0

你没有总结任何价值。如果您的列数等于您的行数,那么您的 for 循环将只运行一次,用于您的最后一项。

procedure TForm1.Button2Click(Sender: TObject);
var
  i, j, s, z, n: integer;
begin
  z:=0;
  for i:=1 to StringGrid1.rowcount-1 do
    for j:=1 to StringGrid1.colcount-1 do
      if i=j then 
      begin
        s:=strtoint(cells[j, i]);
        z:=z+s;
      end;
  Label1.Caption:=inttostr(z);
end;
于 2014-05-08T17:39:02.020 回答