program power(input,output);
var x,result:real; n,m:integer;
begin
read(x,m);
result := 1.0; y := x; n := abs(m);
while n > 0 do
begin
if odd(n) then result := result * y;
y := y*y; n := n div 2
end;
if m < 0 then result := 1/result
writeln(result)
end.
while文の本体の文の実行前と実行後で次の値が保存されているのが味噌です。
(yのn乗)*result
このことと、while文の終了時点でnが0であることから、上のプログラムが正しく計算を行うことがわかります。
program sample(input,output);
var n,m:integer;
begin
read(n);
while n > 0 do
begin
if odd(n) then write('1') else write('0');
n := n div 2
end;
writeln
end.
さて、このプログラムは、nの二進表現を逆向きに表示するプログラムになっている。
文字 … 文字型のデータ
'〈1文字〉'
例) 'a' '1' '$'
※
'〈1文字以上の文字の並び〉'
は、文字型ではなく、文字列型である。
文字型の変数の宣言
var ch, ch:char;
比較の演算子
= <> <= >= < >
がつかえる。
文字の大小関係は、計算機/処理系がつかうコードにより異なる。
次の関係は保証されている:
'A' < 'B' < 'C' <…< 'Z'
'a' < 'b' < 'c' <…< 'z'
'0' < '1' < '2' <…< '9'
それぞれ連続している。(下記†参照)
chr(i) 整数 i を文字に
ord(c) 文字 c を整数に
ord(chr(i)) = i
chr(ord(c)) = c
が成り立つ。
succ(c) 直後の文字
pred(c) 直前の文字
succ(c) = chr(ord(c)+1)
pred(c) = chr(ord(c)-1)
が成り立つ。
†「連続している」とは
'a' 'b' 'c' … 'z'
のordの値がそれぞれ、
97 98 99 … 122
というふうに連続していることである。
if ('a' <= c) and (c <= 'z') then c := chr(ord(c) - ord('a') + ord('A'))
また、aからzまでの繰り返しをしたいとき(例:aからzまでの文字を表示する。)
for i := ord('a') to ord('z') do write(chr(i))
でもいいのですが、もっと単純に、
for ch := 'a' to 'z' do write(ch)
と書くことができます。for文の制御変数で許容されるのは、整数型を含む順序型と呼ばれるものです。文字型、論理型も順序型です。実数は順序型ではありません。
コンパイラ(pc)が機転を利かせて処理してくれる、ということはありません。
統計量
データ x1,...,xnを読み込んで、それらの
n
平均 M = Σ xi/n
i=1
n n
分散 V = Σ (xi-M)^2/n = (Σ xi^2/n) - M^2
i=1 i=1
標準偏差 sd = V^(1/2)
program statistics(input,output);
const n = 5;
var x : array[1..n] of real;
s,m,t,v,sd : real;
i : integer;
begin
for i:=1 to n do read(x[i]);
s:=0;
for i:=1 to n do s := s + x[i];
m := s / n;
t := 0;
for i:=1 to n do t := t + sqr(x[i]);
v := t/n -sqr(m);
sd := sqrt(v);
writeln('mean =', m:7:3);
writeln('variance =', v:7:3);
writeln('standard derivation =', sd:7:3)
end.
実行例
75 61 90 56 82
mean = 72.800
variance =161.360
standard derivation = 12.703
program primes(input,output);
const n = 1000;
type num = 1..n;
var a : array[num] of boolean;
i, p : num;
k : integer;
begin
for i:=1 to n do a[i]:=true;
p:=2;
while p * p <= n do
begin
if a[p] then for i := 2 to n div p do a[p*i] := false;
p := p+1;
end;
k := 0;
for p:=2 to n do
if a[p] then
begin if k mod 10 = 0 then writeln;
write(p:5); k := k+1
end
end.