有些不熟悉 Pascal 的同學,嘗試執行自己 program 時,會發現它完全執行不到;這很可能是 program 中出現了 syntax error。看看以下例子︰
var
a, b, c, d: real;
begin
write('a? '); readln(a);
write('b? '); readln(b);
write('c? '); readln(c);
d = b*b - 4*a*c;
end.
程式中紅色的部份出現了 syntax error(正確的做法應該是使用「:=」),這情況下,program 中連上面三行的 write 及 readln 都不會執行的。
有 syntax error 的 program 是完全不能執行的。
做 Exercise 4-4 時,至少要測試 (test) 以下情況︰
- a=1, b=4, c=3 => Roots = -1, -3
- a=1, b=4, c=4 => roots = -2 (repeated)
- a=1, b=2, c=3 => No real roots
- a=4, b=5, c=-6 => Roots = 0.75, -2
- a=1.5, b=6, c=6 => Roots = -2 (repeated)
大部份同學都能夠做到 Case 1,因為這是題目已有的例子。
有些同學做不到 Case 3 (no real roots),因為他的 program 出現了 run-time error。看看以下例子︰
var
a, b, c, d, x1, x2: real;
begin
write('a? '); readln(a);
write('b? '); readln(b);
write('c? '); readln(c);
x1 := (-b + sqrt(b*b - 4*a*c)) / (2*a);
x2 := (-b - sqrt(b*b - 4*a*c)) / (2*a);
writeln('The roots are ', x1:0:2, ' and ', x2:0:2)
end.
在數學科學過,Case 3 是 no real roots,因為 b2 – 4ac < 0,所以在執行 sqrt 時會發生錯誤。這個 program 沒有 syntax error,因為 program 首三行的 write 及 readln 是有被執行的。
Run-time error 的出現,是因為 program 中有些不合理的操作,例如求負數的平方根、除以零、在執行 read/readln 一個整數時用戶輸入了不是整數的數據、……
有同學把 program 更正為︰
var
a, b, c, d, x1, x2: real;
begin
write('a? '); readln(a);
write('b? '); readln(b);
write('c? '); readln(c);
d := b*b - 4*a*c;
if d > 0 then begin
x1 := (-b + sqrt(d)) / 2*a;
x2 := (-b - sqrt(d)) / 2*a;
writeln('The roots are ', x1:0:2, ' and ', x2:0:2);
end
else if d = 0 then begin
x1 := -b / 2*a;
writeln('The repeated root is ', x1:0:2)
end
else
writeln('No real roots')
end.
試解 4x2 + 5x – 6 = 0。正確答案應該是 0.75 及 -2