1

I've been studying "Algorithms and Data Structures" by N.Wirth. He codes his algorithms in a language he created: Oberon. I finished the book but I have one doubt about this algorithim of page 19 coded in Oberon:

PROCEDURE Power (VAR W: Texts.Writer; N: INTEGER);
    VAR i, k, r: INTEGER;
    d: ARRAY N OF INTEGER;
    BEGIN
        FOR k := 0 TO N-1 DO
            Texts.Write(W, "."); r := 0;
            FOR i := 0 TO k-1 DO
                r := 10*r + d[i]; d[i] := r DIV 2; r := r MOD 2;
                Texts.Write(W, CHR(d[i] + ORD("0")))
            END;
            d[k] := 5; Texts.Write(W, "5"); Texts.WriteLn(W)
        END
    END Power

The resulting output text for N = 10 is
.5
.25
.125
.0625
.03125
.015625
.0078125
.00390625
.001953125
.0009765625

I don´t understand what the instructions in line 10 d[k] := 5; Texts.Write(W, "5"); Texts.WriteLn(W) does:

1) Why you would you d[k] := 5? the program already printed all the output required (d[0] to d[k-1]).

2) why would you print a 5 after that? (Texts.Write(W, "5"))

4

1 回答 1

0

计算利用了最后一位数字总是五的事实。

  1. 除非执行完成,否则当内循环的最后一圈变为d[k]时,在外循环的下一圈读取变量r10*r + d[i]
  2. 该语句Texts.Write(W, "5")需要的计算量(略)少于Texts.Write(W, d[i]).
于 2018-11-04T16:41:16.830 回答