loops - 如何解决此错误?帕斯卡

标签 loops compiler-errors pascal goto

PROGRAM RandomNumber;
Var rand,count,guess : integer;
LABEL correct, loop, wrong, end1;
begin
{Initialization, so that random numbers are drawn}
 Randomize;
  count :=0;
  repeat
      loop:
      count := count+1;
{Random(i) Creates random numbers between 0 and i.}
      rand := Random(10);
      guess := Random(10);
      if rand=guess
      then
          goto correct
      else
          goto wrong;
  until count > 10;
  goto end1;
  correct :
      WriteLn('Correct');
      goto end1;
  wrong :
      WriteLn('False Guess');
      goto loop;
  end1 :
      WriteLn;
end.

该程序的目标是在10次尝试中找到一个随机数。我设法用Free Pascal IDE对其进行了编译,然后出现的问题是该程序直到找到数字后才停止。但是,当我尝试使用在线编译器进行编译时,出现此错误:

prog.pas:在主程序中:

prog.pas:26:错误:“转到”无效目标

是因为标签/goto不能立即跳入循环吗?

最佳答案

最接近的“为什么不起作用?!”答案是exactly as lamas shaikh says:缺少分号。

不要难过这是一件容易错过的事情。 Pascal允许在条件或循环结构之后添加一行代码,或者将begin/end序列作为虚拟语句。这种选择与Pascal使用分号作为语句分隔符而不是终止符产生了严重的相互作用(对解析器设计人员而言是一个很好的区别,但多年来已证明它是微妙且容易出错的,尤其是对于该语言的新手。)谨防缺失和多余分号!

有两件事可以帮助您:始终,始终,始终使用强大,一致,规范的缩进来帮助您显示代码的逻辑结构。而且,您可能会发现,在语句或多语句块可能适合的任何上下文中始终使用begin/end块会更容易(即使该块包含一行)。乍一看似乎很愚蠢,但是当您开始向程序中添加语句(包括临时调试打印语句)时,使用在所有情况下都有效的单个结构确实会有所帮助。

您的程序失败的次要原因不是分号。这是因为您正在使用完全的非结构化方法来控制程序中的流。即使不需要,即使有更简单,更干净,结构更好的替代方法,您也可以在各处GOTO编码。例如,考虑:

PROGRAM RandomNumber;
Var rand, count, guess, MaxGuesses : integer;

begin
    {Initialization, so that random numbers are drawn}
    Randomize;
    MaxGuesses := 10;
    count := 0;
    repeat
        count := count + 1;
        {Random(i) Creates random numbers between 0 and i.}
        rand  := Random(10);
        guess := Random(10);
        if rand = guess
        then begin
            WriteLn('Correct');
            break
        end
        else
            WriteLn('False Guess');
    until count >= MaxGuesses;
    WriteLn;
    if (rand = guess)
    then
        WriteLn('We had a winner (', guess, ') in ', count, ' tries.')
    else
        WriteLn('Sorry! No winner in ', MaxGuesses, ' tries.');
    WriteLn;
end.

编译运行几次,看起来像:
$ ./guess
False Guess
Correct

We had a winner (1) in 2 tries.

$ ./guess
False Guess
False Guess
False Guess
False Guess
False Guess
False Guess
False Guess
False Guess
False Guess
False Guess

Sorry! No winner in 10 tries.

$ ./guess
False Guess
Correct

We had a winner (8) in 2 tries.

Pascal是1960年代和1970年代编程革命的重要组成部分,这些革命使“结构化编程”得到广泛使用。当急切需要更好的结构时,请不要使用较低级别的带有goto的代码。

关于loops - 如何解决此错误?帕斯卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26958570/

相关文章:

delphi - 如何将常量地址分配给pascal指针?

c - 代码O(nlog(n))的T(n)如何?

python - Str 对象不可调用; Python 字典循环错误

c++ - 高级 C 和 C++ 编译 : unable to compile the example program mentioned in the book

c++ - 我解决了一个问题,不知道背后的原因

syntax-error - Pascal库编译错误

delphi - 其他语言上的 ObjectPascal 标识符命名风格

java - 使用字符串创建一个长度为 n、高度为 n 的正方形

arrays - 如果匹配多个相同的数据,如何循环?

python - 确定跨行的唯一字典键