【问题标题】:Why are these lines of code in Pascal necessary?为什么 Pascal 中的这些代码行是必要的?
【发布时间】:2020-04-01 04:00:27
【问题描述】:

下面的 Pascal 示例是在一本专门介绍编程基础知识的书中给出的。 ReadLongint 函数应该检查输入是否以 char 类型编码为 0-9。然后该函数根据检查结果返回真或假,以及用于计算的变量,通过运算符 ord() 呈现为整数。 作为一个新手,我很难弄清楚这段代码是如何工作的。但对我来说更大的谜团是第 9 行的必要性。

    'repeat
         read(c);
         position := position + 1;
     until (c <> #32) and (c <> #10);'

我可以看到这是一个循环,如果您输入 Space 或 Enter,它会不断重复。但是,我检查了没有这些行的程序,用一个简单的 read(c); 代替它,该程序似乎工作得很好。有人可以解释一下这条线在示例中的作用吗?

这是完整的程序:

function ReadLongint(var check: longint): boolean;
     var
         c: char;
         number: longint;
         position: integer;
     begin
         number := 0;
         position := 0;
         repeat
             read(c);
             position := position + 1;
         until (c <> #32) and (c <> #10);
         while (c <> #32) and (c <> #10) do
         begin
             if (c < '0') or (c > '9') then
             begin
                 writeln('Unexpected ''', c, ''' in position: ', position);
                 readln;
                 ReadLongint := false;
                 exit
             end;
             number := number * 10 + ord(c) - ord('0');
             read(c);
             position := position + 1
         end;
         check := number;
         ReadLongint := true
     end;
var
    x, y: longint;
    ok: boolean;
begin
    repeat
        write('Please type the first number: ');
        ok := ReadLongint(x)
    until ok = true;
    repeat
        write('Please type the second number: ');
        ok := ReadLongint(y)
    until ok = true;
    writeln(x, ' times ', y, ' is ', x * y)
end.

【问题讨论】:

  • “而且程序似乎工作得很好” 它仍然按照它应该的方式工作吗?如果输入 123,x 中的最终结果是什么?
  • @Michael 是的,结果是一样的。至少我没有看到任何错误
  • 啊,对,它只是丢弃了前导空格和换行符。所以原始代码允许你在第一个数字前写多个空格。
  • @Michael 哦,没看过这个。非常感谢!
  • 查看第二个循环的条件(实际读取数字的那个),并考虑如果您仅将第一个循环替换为readc 可能包含什么。如果有帮助,请在调试器中逐步执行代码。

标签: function repeat pascal ord


【解决方案1】:

您的readLongInt 函数想要(部分)模仿read/readLn 的行为。如果目标变量是integer(或real)或char 值,read/readLn 的行为会略有不同。 ISO Standard 7185 是这样说的:

c) 如果v 是具有integer-type(或其子范围)的variable-accessread(f, v) 应满足以下要求。 s 的任何组件都不应等于 end-of-liner 的组成部分,如果有的话,应该每个,并且 (s ~t ~u).first 不应该等于 char-type 值空间或行尾。 […]

翻译成简单的英语:解释数字时忽略前导空格和换行符(即integer [或real] 变量作为目的地)。这与read/readLnchar 变量的组合完全不同,其中' ' 是一个合法 值,因此它不是“跳过” ”,你知道的。

until (c &lt;&gt; #32) and (c &lt;&gt; #10) 循环试图模仿read(check) 的行为,尽管实际使用的read(c) 只读取一个char 值,一个接一个。

PS:看到ok = true 总是让我畏缩。我希望,不像教科书的作者,知道= true是多余的,只是一个身份。

【讨论】:

    猜你喜欢
    • 2019-12-28
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多