我正在尝试编写代码来计算构成stringgrid主对角线的单元格中所有数字的总和,但我得到的结果只是在右下角单元格中输入的数字I.这是我的代码:
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.
我错过了什么?提前致谢
答案 0 :(得分:0)
你没有总结任何价值观。如果您的columcount等于您的rowcount,那么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;