【问题标题】:Got "Boolean" expected "LongInt" pascal得到“布尔”预期“LongInt”帕斯卡
【发布时间】:2015-03-23 09:23:01
【问题描述】:

我的插入排序算法出现此错误:

insertionsort.lpr(19,17) 错误:不兼容的类型:得到“Boolean”预期“LongInt”

这是我的代码的第 19 行

 while j > 0 and A[j]>key do            

我已经尝试在整个互联网上搜索,但我找不到任何语法错误或任何东西。

如果有帮助,这里是完整的代码:

program instert;
uses crt;
const
  N = 5;
var
   i:integer;
   j:integer;
   key:integer;
   A : Array[1..N] of Integer;


procedure insertionsort;
  begin
  for i := 2 to N  do
    begin
    key := A[1];
    j:= i - 1;
        while j > 0 and A[j]>key do
        begin
          A[j+1] := A[j] ;
          j := j-1;
        end;
    A[j+1] := key ;
   end;
 end;

begin
  A[1]:= 9;
  A[2]:= 6;
  A[3]:= 7;
  A[4]:= 1;
  A[5]:= 2;
  insertionsort;
end.

我在冒泡排序算法上也遇到了同样的错误。这是错误行

bubblesort.lpr(26,14) 错误:不兼容的类型:得到“Boolean”预期“LongInt”

这是我算法的第 26 行:

 until flag = false or N = 1 ;   

这是完整的代码:

program bubblesort;
uses crt;

var
  flag:boolean;
  count:integer;
  temp:integer;
  N:integer;
  A : Array[1..N] of Integer;

procedure bubblesort ;
begin
  Repeat
    flag:=false;
    for count:=1 to (N-1)  do
    begin
    if A[count] > A[count + 1] then
       begin
       temp := A[count];
       A[count] := A[count + 1];
       A[count] := temp;
       flag := true;
       end;
    end;
    N := N - 1;
  until flag = false or N = 1 ;
end;

begin
  A[1]:= 9;
  A[2]:= 6;
  A[3]:= 7;
  A[4]:= 1;
  A[5]:= 2;
  N := 5;
  bubblesort;
end.

【问题讨论】:

  • 这是一个优先问题。 > 的优先级低于 and,因此请使用括号:while (j > 0) and (A[j]>key) do。同样,你需要until (flag = false) or (N = 1) ;(或者只是until not flag or (N = 1) ;
  • @lurker 感谢现在程序正常工作
  • @lurker 在 cmets 中回答问题时,有人几乎和我一样糟糕;)
  • @CodesInChaos 是的,这是我遭受的一种病态。 ;)

标签: boolean pascal long-integer bubble-sort insertion-sort


【解决方案1】:

在 Pascal 中,布尔运算符 andor 的优先级高于比较运算符 >= 等。所以在表达式中:

while j > 0 and A[j] > key do

鉴于and 具有更高的优先级,Pascal 认为这是:

while (j > (0 and A[j])) > key do

0 and A[j] 按位计算and(因为参数是整数),结果是一个整数。然后比较,j > (0 and A[j]) 被评估为布尔结果,留下一个与> key 的检查,即boolean > longint。然后,您会得到一个错误,即预期为 longint 而不是 boolean 用于算术比较。

解决方法是加括号:

while (j > 0) and (A[j] > key) do ...

同样的问题也适用于这个语句:

until flag = false or N = 1 ;

这会产生错误,因为or 的优先级高于=。所以你可以加括号:

until (flag = false) or (N = 1);

或者,更规范的布尔值:

until not flag or (N = 1);    // NOTE: 'not' is higher precedence than 'or'

当对运算符的优先级有疑问时,使用括号是个好主意,因为它消除了对将要发生什么顺序操作的疑问。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 2016-08-23
    • 2011-02-03
    • 1970-01-01
    相关资源
    最近更新 更多