线性方程式,不兼容的类型BOOLEAN / LONGINT

时间:2018-11-23 10:45:45

标签: pascal operator-precedence

我在Pascal中进行了线性方程的练习,并且为比较输入数字创建了简单的代码,但是当我尝试运行它时。我对不兼容的类型got BOOLEAN and expected LONGINT有疑问。

program LinearEquation;

var
  a, b: real;

begin
  readln(a, b);

  if (b = 0 and a = 0) then
    writeln('INFINITY')
  else if (b = 0 and a <> 0) then
    writeln(1)
  else if (a = 0 and b <> 0) then
    writeln(0)
  else if(b mod a = 0) then
    writeln(1);

  readln;

end.

13 / 9 rownan~1.pas
 Error: Incompatible types: got "BOOLEAN" expected "LONGINT"
15 / 14 rownan~1.pas
 Error: Incompatible types: got "BOOLEAN" expected "LONGINT"
17 / 14 rownan~1.pas
 Error: Incompatible types: got "BOOLEAN" expected "LONGINT"
17 / 14 rownan~1.pas
 Error: Incompatible types: got "BOOLEAN" expected "LONGINT"

1 个答案:

答案 0 :(得分:2)

至少在modern Delphi中,and的优先级高于=,所以

a = 0 and b = 0

被解释为

(a = (0 and b)) = 0.

但是and运算符不能接受整数和浮点值作为操作数(但是,两个整数本来可以)。因此是错误。

如果ab是整数,则0 and b将是0b的按位相加,即0 。因此,我们本来可以

(a = 0) = 0.

这将读取true = 0(如果a等于0)或false = 0(如果a0不同)。但是布尔值不能与整数进行比较,因此编译器会对此抱怨。

不过,这只是一个学术练习。显然,你的意图是

(a = 0) and (b = 0).

只需添加括号:

if (b = 0) and (a = 0) then
  writeln('INFINITY')
相关问题