我试图重写一个while do循环作为Pascal中的for do循环,请有一种方法将下面的代码重写为for循环语句…并确定哪个更好,为什么?
Thanks in advance.
代码
program Quadractics;
uses crt;
const n=10;
VAR
a,b,c,d,e,x1,x2:real;
k:Integer;
BEGIN
k:= 0;
while k<n DO
begin
writeln('Input the values for variables a,b,c');
readln(a,b,c);
e:=2*a;
d:=sqr(b)-(4.0*a*c);
if d>=0 then
begin
x1:=(-b+sqrt(d)) /e;
x2:=(-b-sqrt(d)) /e;
writeln('The resulting roots of the above equation are x1= ', x1 , ' and x2= ', x2);
end
else
begin
write('complex root values are ');
write('x1 = ', '(',-b, '+√',d,')','/',e ,', ');
write('and','; ');
write('x2 = ', '(',-b, '-√',d,')','/',e ,', ');
end;
k:=k+1;
end;
END.
由于我不想破坏你的作业,我给你以下提示:
伪代码 中的while
循环loopcounter = startvalue
while loopcounter < endvalue do // could also be loopcounter <= endvalue
begin
code to perform on every loop
loopcounter = loopcounter + 1
end
伪代码
中的for
循环for loopcounter = startvalue to endvalue // could also be to endvalue-1
begin
code to perform on every loopcounter
end
思考并比较endvalue
表达方式的差异
最后一个提示:始终遵循缩进规则,这样更容易阅读代码的结构和功能。