1

为什么过程会影响循环?

当我将一个过程Line放在一个循环中for时,它会变得无穷无尽,我只需关闭控制台窗口并丢失所有未保存的数据。

这是我的程序的完整代码,并且有注释(最后)指出了问题:

uses crt;
var
n, i :integer;
a, b, h, x, res :real;


function func_1(y :real) : real;
  begin
    func_1:= (y*y*y*y) * (1 + sin(y) * sin(y));
  end;


function func_2(y :real) : real;
  begin
    func_2:= sin(y/2) / cos(y/2);
  end;


function func_3(y :real) :real;
  begin
    func_3:= sin(y) * cos(y);
  end;

procedure Line(sideSymbolLeft: char; usualSymbol: char;
               divideSymbol: char; sideSymbolRight: char);
  begin
    write(char(sideSymbolLeft));
    for i := 2 to 75 do
      begin
        write(char(usualSymbol));
        if ( (i mod 19) = 0 ) then
          write(char(divideSymbol));
      end;
    writeln(char(sideSymbolRight));
  end;


begin
  clrscr;

  a:= 0;
  b:= 2 * pi;
  n:= 7;
  h:= ( b - a ) / n;


  Line(char(201), char(205), char(205), char(187));
  writeln(char(186),'Functions of one variable':50,char(186):28);
  Line(char(204), char(205), char(203), char(185));
  writeln(char(186),'    Argument X    ',char(186),'  x^4*(1+sin^2(x)) ',
          char(186),'      tg(x/2)      ',char(186),'   sin(x)*cos(x)  ',char(186));

  for i:= 0 to n do (* calculating all Xs (arguments) *)
    begin
      x:= a + (i * h);
      write('   ');
      write(x:8:3);

      res:= func_1(x);
      write('              ');
      write(res:8:3);

      res:= func_2(x);
      write('   ');
      write(res:8:3);

      res:= func_3(x);
      write('         ');
      writeln(res:8:3);

      (* HERE IS THAT PROCEDURE *)
      (* When I put it here, the loop becomes endless *)
      (* and I have to close the console (and lose all unsaved data) *)
      Line(char(204), char(205), char(203), char(185));

    end;


  readln;
end.
4

1 回答 1

3

您同时i在两个地方使用相同的全局循环计数器变量(在Line调用它的主体循环内部和内部)。(这是全局变量不好的原因之一,顺便说一句。)

// In Line()
for i := 2 to 75 do

// In calling code
for i:= 0 to n do (* calculating all Xs (arguments) *)

这意味着每次第二个循环运行并调用Line()时,计数器都会重置(内部Line)为 2。

在里面添加一个局部变量Line来处理那里的计数器:

procedure Line(sideSymbolLeft: char; usualSymbol: char;
               divideSymbol: char; sideSymbolRight: char);
var
  Ctr: Integer;
begin
  write(char(sideSymbolLeft));
  for Ctr := 2 to 75 do
  begin
    write(char(usualSymbol));
    if ( (Ctr mod 19) = 0 ) then
      write(char(divideSymbol));
  end;
  writeln(char(sideSymbolRight));
end;
于 2013-09-27T19:06:02.927 回答