If statement 自由Pascal,嵌套ifs和ELSE的问题
有人能告诉我我的代码有什么问题吗?它应该解二次方程:If statement 自由Pascal,嵌套ifs和ELSE的问题,if-statement,nested,pascal,If Statement,Nested,Pascal,有人能告诉我我的代码有什么问题吗?它应该解二次方程: 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=
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.
这是通过对程序进行一些轻微的修改来完成的,以使输出更具可读性,但大部分代码(特别是计算)未被触及。和?它在做什么与你想要的不同?您是否希望有人编译、运行、测试它(基于由“解二次方程”组成的规范),这样您就不必为您的问题付出任何努力?通过正确设置格式,您可以看到缺少一些
end
。