Basic Pascal Tutorial/Chapter 3/Solution/ja

From Lazarus wiki
Revision as of 15:28, 11 August 2015 by Derakun (talk | contribs)
Jump to navigationJump to search

Template:Solution 3/ja

3Ea - 解答 (著者: Tao Yue, 状態: 原文のまま修正なし)

フィボナッチ数列問題の解答

(* 著者:    Tao Yue
   日付:      19 July 1997
   記述:
      最初の10個のフィボナッチ数列の数を求める。
   Version:
      1.0 - original version
*)

program Fibonacci;

var
   Fibonacci1, Fibonacci2 : integer;
   temp : integer;
   count : integer;

begin    (* Main *)
   writeln ('最初の10個のフィボナッチ数列は:');
   count := 0;
   Fibonacci1 := 0;
   Fibonacci2 := 1;
   repeat
      write (Fibonacci2:7);
      temp := Fibonacci2;
      Fibonacci2 := Fibonacci1 + Fibonacci2;
      Fibonacci1 := Temp;
      count := count + 1
   until count = 10;
   writeln;

   (* もちろん、この問題をとくために FOR ループや WHILE ループを使うこともできる。 *)

end.     (* Main *)

2の累乗値の解答

(* 著者:    Tao Yue
   日付:      13 July 2000
   記述:
      20000未満の2の累乗値をすべて求め、1行に5つ表示する。
   Version:
      1.0 - original version
*)

program PowersofTwo;

const
   numperline = 5;
   maxnum = 20000;
   base = 2;

var
   number : longint;
   linecount : integer;

begin    (* Main *)
   writeln ('Powers of ', base, ', 1 <= x <= ', maxnum, ':');
   (* ループの設定 *)
   number := 1;
   linecount := 0;
   (* ループ *)
   while number <= maxnum do
      begin
         linecount := linecount + 1;
         (* 行の最初の数字でなければカンマとスペースを表示させる *)
         if linecount > 1 then
            write (', ');
         (* 数字を表示させる *)
         write (number);
         (* 数列の最後の数字でなく、行の最後の数字ならコンマを表示し、次の行に行く。 *)
         if (linecount = numperline) and not (number * 2 > maxnum) then
            begin
               writeln (',');
               linecount := 0
            end;
         (* 数字を増やす *)
         number := number * base;
      end;  (* while *)
   writeln;

   (* このプログラムも REPEAT..UNTIL ループを用いて書き換えることができる。 *)

end.     (* Main *)

Note that I used three constants: the base, the number of powers to display on each line, and the maximum number. This ensures that the program can be easily adaptable in the future.

Using constants rather than literals is a good programming habit to form. When you write really long programs, you may refer to certain numbers thousands of times. If you hardcoded them into your code, you'd have to search them out. Also, you might use the same value in a different context, so you can't simply do a global Search-and-Replace. Using a constant makes it simpler to expand the program.

Also note that I used the longint type for the number variable. This is because to fail the test number <= 20000, number would have to reach 32768, the next power of two after 16384. This exceeds the range of the integer type: -32768 to 32767. (try it without longint and see what happens)

previous contents next