next up previous
Next: 課題 Up: 無題 Previous: 関係演算子

2次方程式の解法

次に示すプログラムは、二次方程式

displaymath153

の係数a,b,c( tex2html_wrap_inline163 )を実数値の入力として読みこんで、 実根が存在するときには2つの実根を出力するプログラムです。

2次方程式の根の公式によると判別式を

displaymath154

とおくと、二つの根は、 tex2html_wrap_inline165 ならば tex2html_wrap_inline167
D < 0ならば tex2html_wrap_inline171

でした。これに素直に従ってプログラムを作成すると、

program eq1(input,output);
var a, b, c, d, sd, x1, x2 : real;
begin
    read(a,b,c);
    if a = 0 then 
        writeln('a should be non-zero')
    else
    begin
        d := sqr(b) - 4*a*c;
        if d >= 0 then
        begin
            sd := sqrt(d);
            x2 := (-b - sd)/(2*a);
            x1 := (-b + sd)/(2*a);
            writeln(x1);
            writeln(x2)
        end
        else writeln('Imaginary root')
    end
end.

となります。




Mon Jun 30 01:42:14 JST 1997