免费帕斯卡,嵌套ifs和其他麻烦



有人可以告诉我我的代码出了什么问题吗?它应该求解二次方程:

program quadraticeq;
uses crt;
var
    a,b,c,x1,x2,R1,I1,R2,I2,D: integer;
    p:1..4;
begin
    writeln (output, 'Enter a,b i c:');   {ax^2 + bx + c = 0}
    readln (a,b,c);
    D:=sqr(b)-4*a*c;  {discriminant}
    if a=0 then
        p:=1
    else  
        if D=0 then begin
            p:=2;
            x1:=(-b)/(2*a);
            end
        else
            if D>0 then begin
                p:=3;
                x1:=(-b+sqrt(D))/(2*a);
                x2:=(-b-sqrt(D))/(2*a);
            end
            else begin
                p:=4;
                R1:=(-b)/(2*a);
                I1:=sqrt(-D)/(2*a);
                R2:=-R1;
                I2:=-I1;
        end;
    case p of
    1:  writeln (output, 'Wrong entry! Quantificator a mustnt be zero!');
    2:  writeln (output, 'Double root of the equation is: x1=x2=',x1);
    3:  writeln (output, 'Roots of the equation are x1=',x1,'and x2=',x2,'.');
    4:  writeln (output, 'Complex roots of the equation are x1=',R1,'+i',I1,' and x2=',R2,'+i',I2,'.');
    end;
end.

当我在FreePascal下编译你的代码时,我得到:

Compiling main.pas                                                               
main.pas(17,21) Error: Incompatible types: got "Double" expected "SmallInt"      
main.pas(22,33) Error: Incompatible types: got "Extended" expected "SmallInt"    
main.pas(23,33) Error: Incompatible types: got "Extended" expected "SmallInt"    
main.pas(27,25) Error: Incompatible types: got "Double" expected "SmallInt"      
main.pas(28,29) Error: Incompatible types: got "Extended" expected "SmallInt"    
main.pas(40) Fatal: There were 5 errors compiling module, stopping               
Fatal: Compilation aborted                                                       

所以它看起来像整数和浮点类型之间的冲突。当我将除 p 以外的所有变量切换为类型 real 时:

var
    a,b,c,x1,x2,R1,I1,R2,I2,D: real;
    p:1..4;

然后它编译得很好。

并且,当使用已知值执行时:

   (x + 1)(x - 3) = 0
=>   x^2 -2x -3   = 0

明白了:

Enter a, b, c:                                                                  
1 -2 -3                                                                          
Roots of the equation are x = 3.00000 or -1.00000.

这是通过对程序进行一些轻微修改以使输出更具可读性来完成的,但大部分代码(特别是计算)保持不变。

最新更新