得到“Boolean”预期“LongInt”pascal

问题描述 投票:0回答:2

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

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.
boolean pascal long-integer bubble-sort insertion-sort
2个回答
7
投票

在 Pascal 中,布尔运算符

and
or
的优先级高于比较运算符
>
=
等。因此在表达式中:

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'

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


0
投票

得到布尔预期 lomgint 这是我的行 tota:=totl=points[S]

© www.soinside.com 2019 - 2024. All rights reserved.