为什么程序会对循环产生影响?
当我在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.
答案 0 :(得分:3)
您在两个地方同时使用相同的全局循环计数器变量i
(在Line
内部和调用它的主体循环中)。 (这是全局变量不好的原因之一,BTW。)
// 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;