尝试循环输出时的结果不同

时间:2015-02-08 06:53:19

标签: arrays delphi output

这是我的代码,假设我有这个

a[i,j];

然后我算上这个

//count b
for i := 0 to 4 do 
begin
  for j := 0 to 5 do 
  begin
    b[0,j] := nilEn * a[i,j];
    b[1,j] := nilPro * a[i,j];
    b[2,j] := nilKar * a[i,j];
    b[3,j] := nilLem * a[i,j];
    b[4,j] := nilVit * a[i,j];
    Memo1.Lines.Append(FloatToStr(b[i,j]));
  end;
end;

这是问题,当我比较memo1和memo2的结果时,它会给出不同的结果

for i := 0 to 4 do
begin
  for j := 0 to 5 do
  begin
    Memo2.Lines.Append(FloatToStr(b[i,j]));
  end;
end;

1 个答案:

答案 0 :(得分:0)

这是因为你做的不同。

for i := 0 to 4 do 
  for j := 0 to 5 do 
  begin
    b[0,j] := nilEn * a[i,j];
    b[1,j] := nilPro * a[i,j];
    b[2,j] := nilKar * a[i,j];
    b[3,j] := nilLem * a[i,j];
    b[4,j] := nilVit * a[i,j];
    Memo1.Lines.Append(FloatToStr(b[i,j]));
  end;

应该是:

const 
   Values : array[0..4] of integer = (nilEn, nilPro, nilKar, nilLem, nilVit);

for i := 0 to 4 do 
begin
  for j := 0 to 5 do 
  begin
    b[i,j] := Values[i] * a[i,j];
    Memo1.Lines.Append(FloatToStr(b[i,j]));
  end;
end;

另一个值为变量的解决方案:

var
   Values : array[0..4] of integer;
   Values[0] := nilEn;
   Values[1] := nilPro; 
   Values[2] := nilKar; 
   Values[3] := nilLem; 
   Values[4] := nilVit;


for i := 0 to 4 do 
begin
  for j := 0 to 5 do 
  begin
    b[i,j] := Values[i] * a[i,j];
    Memo1.Lines.Append(FloatToStr(b[i,j]));
  end;
end;