Error incompatible types got single expected smallint

В этом разделе описаны все ошибки, которые могут случиться при проверке типов.

В этом разделе описаны все ошибки, которые могут случиться при проверке типов.

Сообщение

Описание

Error: Type mismatch

Это может произойти во многих случаях:

Назначенная вами переменная отличается от типа, который используется в выражении

Вы вызываете функцию или процедуру с параметрами, которые несовместимы с параметрами в объявлении функции или процедуры

Error: Incompatible types: got «Сообщ1» expected «Сообщ2»

Невозможно преобразование между двумя типами. Ещё одна причина – типы объявлены в разных объявлениях:

Var A1 : Array[1..10] Of Integer;
  A2 : Array[1..10] Of Integer;
Begin
A1:=A2; {Этот оператор также даёт такую ошибку, потому
          что выполняется строгая проверка типов Pascal}
End.

Error: Type mismatch between «Сообщ1» and «Сообщ2»

Типы не являются эквивалентными.

Error: Type identifier expected

Идентификатор не является типом, или вы забыли указать идентификатор type.

Error: Variable identifier expected

Это случается, если вы помещаете константу в процедуру (такую как Inc или Dec), в то время как процедура требует переменной. Для таких процедур в качестве параметров можно помещать только переменные.

Error: Integer expression expected, but got «Сообщение»

Компилятор ожидает выражения типа integer, но получает другой тип.

Error: Boolean expression expected, but got «Сообщение»

Выражение должно быть типа boolean. Оно должно возвращать True или False.

Error: Ordinal expression expected

Выражение должно быть порядкового типа, то есть максимум типа Longint. Эта ошибка случается, например, если вы указали второй параметр процедуры Inc или Dec, который не соответствует порядковому типу.

Error: pointer type expected, but got «Сообщение»

Переменная или выражения не являются указателем. Это случается, если вы помещаете переменную, которая не является указателем, в New или Dispose.

Error: class type expected, but got «Сообщение»

Переменная или выражение не являются типом class. Это обычно случается, если

1.Родительский класс в объявлении класса не является классом

2.Обработчик исключения (On) cсодержит идентификатор типа, который не является классом.

Error: Can’t evaluate constant expression

Эта ошибка может случиться, если границы объявленного вами массива не обозначены порядковыми константами.

Error: Set elements are not compatible

Вы пытаетесь выполнить операцию с двумя множествами, в то время как типы элементов этих множеств не являются одинаковыми. Базовые типы множеств должны быть одинаковыми при объединении.

Error: Operation not implemented for sets

Некоторые бинарные операторы не определены для множеств. Это операторы: div, mod, **, >= и <=. Последние два могут быть определены для множеств в будущих версиях.

Warning: Automatic type conversion from floating type to COMP which is an integer type

Обнаружено явное преобразование типов из real в comp. s encountered. Поскольку comp – это 64-битное целое число, то это может вызвать ошибку.

Hint: use DIV instead to get an integer result

Если подсказки включены, то целочисленное деление с оператором ‘/‘ приведёт к этому сообщению, потому что результатом будет вещественный тип.

Error: string types doesn’t match, because of $V+ mode

Если выполняется компиляция в режиме {$V+}, то строка, передаваемая вами в качестве параметра, должна быть точно такого же типа, как параметр процедуры.

Error: succ or pred on enums with assignments not possible

Если вы объявили перечисляемый тип в стиле С, например, так:

Tenum = (a,b,e:=5);

То вы не сможете использовать функции Succ или Pred с этим перечислением.

Error: Can’t read or write variables of this type

Вы пытаетесь прочитать или записать переменную из файла или в файл текстового типа, который не поддерживает тип переменной. Только целочисленные типы, вещественные, pchars и strings можно читать из файла или записывать в текстовый файл. Логические переменные можно только записывать в текстовый файл.

Error: Can’t use readln or writeln on typed file

readln и writeln можно использовать только с текстовыми файлами.

Error: Can’t use read or write on untyped file.

read и write допускаются только для текстовых или типизированных файлов.

Error: Type conflict between set elements

Это означает, что не менее одного элемента множества имеют неправильный тип.

Warning: lo/hi(dword/qword) returns the upper/lower word/dword

Free Pascal поддерживает перегруженную версию lo/hi для longint/dword/int64/qword, которые возвращают наименьшее/наибольшее (результат типа слово/двойное слово) значение аргумента. Turbo Pascal позволяет использовать 16-битные lo/hi, которые возвращают биты 0..7 для lo и биты 8..15 для hi. Если вы хотите получить поведение, аналогичное Turbo Pascal, вы должны использовать приведение типов к word или integer.

Error: Integer or real expression expected

Первый аргумент для str должен быть типа real или integer.

Error: Wrong type «Сообщение» in array constructor

Вы пытаетесь использовать тип в конструкторе массива, который недопустим.

Error: Incompatible type for arg no. Сообщ1: Got «Сообщ2», expected «Сообщ3»

Вы пытаетесь передать неправильный тип в указанный параметр.

Error: Method (variable) and Procedure (variable) are not compatible

Вы не можете связать метод с процедурной переменной или процедуру с указателем на метод.

Error: Illegal constant passed to internal math function

Аргумент-константа, переданный в функцию ln или sqrt выходит за пределы диапазона для этой функции.

Error: Can’t take the address of constant expressions

Невозможно получить адрес выражения-константы, потому что оно не записывается в память. Вы можете попробовать сделать типизированную константу. Эта ошибка может также появиться, если вы пытаетесь поместить свойство в параметр var.

Error: Argument can’t be assigned to

Только выражение, которое может быть в левой части присваивания, может быть передано как вызов по ссылке аргумента. Примечание: Свойства могут использоваться в левой части присваивания, тем не менее, они не могут использоваться как аргументы.

Error: Can’t assign local procedure/function to procedure variable

Не допускается присваивать локальные процедуры/функции процедурным переменным, потому что соглашение о вызовах локальных процедур/функций отличаются. Вы можете только присвоить локальную процедуру/функцию пустому указателю.

Error: Can’t assign values to an address

Не допускается присваивать значение адресу переменной, константы, процедуры или функции. Вы можете попытаться выполнить компиляцию с опцией -So, если идентификатор является процедурной переменной.

Error: Can’t assign values to const variable

Не допускается присваивать значение переменной, которая объявлена как константа. Обычно параметр объявляется как константа. Чтобы иметь возможность изменять значение, передавайте параметр по значению или параметр по ссылке (используя var).

Error: Array type required

Если вы хотите получить доступ к переменной, используя индекс ‘[<x>]‘, то тип должен быть массивом. В режиме FPC указатель также допускается.

Error: interface type expected, but got  «»Сообщение»

Компилятор ожидал для нумератора имя типа интерфейса, но получил нечто другое. Следующий код приведёт к этой ошибке:

Type
TMyStream = Class(TStream,Integer)

Hint: Mixing signed expressions and longwords gives a 64bit result

Если вы делите (или вычисляете модуль) выражения со знаком с типом longword (или наоборот), или если вы имеете переполнение и/или включена проверка диапазона и используется арифметическое выражение (+, -, *, div, mod), в котором оба числа со знаком и появляется longwords, то всё это вычисляется как 64-битная арифметическая операция, которая медленнее, чем обычная 32-битная. Вы можете избежать этого при помощи преобразования типа одного из операндов в подходящий для результата и другого операнда.

Warning: Mixing signed expressions and cardinals here may cause a range check error

Если вы используете бинарный оператор (and, or, xor) и один из операндов — это longword, в то время как другой – это выражение со знаком, то, если проверка диапазона включена, вы можете получить ошибку проверки диапазона, потому что в этом случае оба операнда преобразуются в longword перед выполнением операции. Вы можете избежать этого при помощи преобразования типа одного из операндов в подходящий для результата и другого операнда.

Error: Typecast has different size (Сообщ1 -> Сообщ2) in assignment

Преобразование типа при отличающихся размерах не допускается, когда переменная используется в присваивании.

Error: enums with assignments can’t be used as array index

Если вы объявили перечисляемый тип, который имеет С-подобные присваивания, как показано ниже:

Tenum = (a,b,e:=5);

Вы не можете использовать его как индекс массива.

Error: Class or Object types «Сообщ1» and «Сообщ2» are not related

Выборка из одного класса в другой, в то время как класс/объект не являются связанными. Вероятно, это ошибка ввода.

Warning: Class types «arg1» and «arg2» are not related

Выборка из одного класса в другой, в то время как класс/объект не являются связанными. Вероятно, это ошибка ввода.

Error: Class or interface type expected, but got «arg1»

Компилятор ожидал имя класса или интерфейса, но получил другой тип или идентификатор.

Error: Type «Сообщение» is not completely defined

Эта ошибка случается, если тип не завершён, например, тип pointer, который указывает на неопределённый тип.

Warning: String literal has more characters than short string length

Размер строки-константы, которая связана с shortstring, больше максимального размера для shortstring (255 символов).

Warning: Comparison is always false due to range of values

Это сравнение беззнакового значения и константы со знаком, которая меньше нуля. По причине преобразования оператор всегда будет возвращать FALSE. Выполните явное преобразование константы в правильный диапазон, чтобы избежать этой проблемы.

Warning: Comparison is always true due to range of values

Это сравнение беззнакового значения и константы со знаком, которая меньше нуля. По причине преобразования оператор всегда будет возвращать TRUE. Выполните явное преобразование константы в правильный диапазон, чтобы избежать этой проблемы.

Warning: Constructing a class «Сообщ1» with abstract method «Сообщ2»

Например, создаваемый класс содержит неисполняемые абстрактные методы. Имеется вероятность, что случится ошибка времени исполнения 211 в коде, если эта процедура будет когда-либо вызвана. Все абстрактные методы должны быть перегружаемыми.

Hint: The left operand of the IN operator should be byte sized

Левый операнд в операторе IN не является порядковым или перечислением, который помещается в 8 бит. Это может привести к ошибке проверки диапазона. На текущий момент оператор in поддерживает левый оператор только в пределах байта. В случае с перечислениями, размер элемента перечисления может изменяться опциями {$PACKENUM} или {$Zn}.

Warning: Type size mismatch, possible loss of data / range check error

Это случается, когда меньшему типу присваивается значение, большее, чем исходный тип. Это означает, что может произойти ошибка проверки диапазона или уменьшение значения.

Hint: Type size mismatch, possible loss of data / range check error

Это случается, когда меньшему типу присваивается значение, большее, чем исходный тип. Это означает, что может произойти ошибка проверки диапазона или уменьшение значения.

Error: The address of an abstract method can’t be taken

Не найдено тело абстрактного метода, поэтому адрес абстрактного метода не может быть назначен.

Error: Assignments to formal parameters and open arrays are not possible

Вы пытаетесь присвоить значение формальному параметру (нетипизированный var, const или out), или открытому массиву.

Error: Constant Expression expected

Компилятор ожидал выражение-константу, но получил выражение- переменную.

Error: Operation «Сообщ1» not supported for types «Сообщ2» and «Сообщ3»

Операция не допускается для указанных типов.

Error: Illegal type conversion: «Сообщ1» to «Сообщ2»

Когда выполняете преобразование типов, вы должны понимать, что размеры переменной и типа назначения одинаковы.

Hint: Conversion between ordinals and pointers is not portable

Если вы преобразуете тип pointer в longint (или наоборот), то код не будет компилироваться на машинах, использующих 64-разрядную адресацию.

Warning: Conversion between ordinals and pointers is not portable

Если вы преобразуете тип pointer в порядковый тип с другим размером (или наоборот), то могут возникнуть проблемы. Это предупреждение помогает в поиске 32-битного специального кода, где cardinal/longint используются для преобразования указателей в порядковые типы. Решением проблемы является использование вместо этого типов ptrint/ptruint.

Error: Can’t determine which overloaded function to call

Вы вызываете перегруженную функцию с параметром, который не связан с каким-либо объявленным списком параметров, например, когда вы имеете объявленную функцию с параметрами word и longint, а затем вызываете её с параметром типа integer.

Error: Illegal counter variable

Переменная для цикла for должна быть порядкового типа. Переменные циклов не могут быть вещественными числами или строками.

Warning: Converting constant real value to double for C variable argument, add explicit typecast to prevent this.

В C значения вещественных констант по умолчанию имеют тип double. Из этих соображений, когда вы передаёте вещественную константу в функцию С в качестве параметра, компилятор FPC по умолчанию преобразует её в тип double. Если вы хотите контролировать этот процесс, добавьте для константы явное преобразование в нужный тип.

Error: Class or COM interface type expected, but got «Сообщение»

Некоторые операторы, такие как AS, применяются только для классов или COM-интерфейсов.

Error: Constant packed arrays are not yet supported

Вы не можете объявить битовый (упакованный) массив как типизированную константу.

Error: Incompatible type for arg no. Сообщ1: Got «Сообщ2» expected «(Bit)Packed Array»

Компилятор ожидает битовый (упакованный) массив как указанный параметр.

Error: Incompatible type for Сообщение no. Сообщ1: Got «Сообщ2» expected «»(not packed) Array»

Компилятор ожидает регулярный (то есть НЕ упакованный) массив как указанный параметр.

Error: Elements of packed arrays cannot be of a type which need to be initialised

Поддержка упакованных массивов, которым необходима инициализация (таких как ansistrings, или записей, содержащих ansistrings), пока не реализована.

Error: Constant packed records and objects are not yet supported

Вы не можете объявить битовый (упакованный) массив как типизированную константу в данное время.

Warning: Arithmetic «Сообщение» on untyped pointer is unportable to {$T+}, suggest typecast

Сложение/вычитание из нетипизированных указателей может работать по разному в {$T+}. Используёте преобразование типов для типизированных указателей.

Error: Can’t take address of a subroutine marked as local

Нельзя получить адрес подпрограммы, помеченной как локальная.

Error: Can’t export subroutine marked as local from a unit

Подпрограмма, помеченная как локальная, не может быть экспортирована из модуля.

Error: Type is not automatable: «Сообщение»

Только byte, integer, longint, smallint, currency, single, double, ansistring, widestring, tdatetime, variant, olevariant, wordbool и все интерфейсы являются automatable.

Hint: Converting the operands to «Сообщение» before doing the add could prevent overflow errors.

Сложение двух типов может вызвать ошибку переполнения. Обычно вы конвертируете результат в больший тип. Вы должны предотвращать такие ошибки, преобразуя операнды в этот тип перед сложением.

Hint: Converting the operands to «Сообщение» before doing the subtract could prevent overflow errors.

Вычитание между двумя типами может вызвать ошибку переполнения. Обычно вы конвертируете результат в больший тип. Вы должны предотвращать такие ошибки, преобразуя операнды в этот тип перед вычитанием.

Hint: Converting the operands to «Сообщение» before doing the multiply could prevent overflow errors.

Умножение между двумя типами может вызвать ошибку переполнения. Обычно вы конвертируете результат в больший тип. Вы должны предотвращать такие ошибки, преобразуя операнды в этот тип перед умножением.

Warning: Converting pointers to signed integers may result in wrong comparison results and range errors, use an unsigned

Виртуальное адресное пространство на виртуальных машинах располагается от $00000000 до $ffffffff. Многие операционные системы позволяют выделять память с адресами выше $80000000. Например, как WINDOWS, так и LINUX, допускают использование указателей в диапазоне от $0000000 до $bfffffff. Если вы преобразуете типы со знаком, это может вызвать ошибки переполнения и проверки диапазона, но также $80000000 < $7fffffff. Это может вызвать случайную ошибку в коде, подобно этому: «if p>q».

Error: Interface type Сообщение has no valid GUID

Если применяется оператор as для интерфейса или класса, то интерфейс (то есть правый операнд оператора as) должен иметь правильный GUID.

Error: Invalid selector name

Селектор Objective-C не может быть пустым, он должен быть правильным идентификатором или одинарным двоеточием, а если он содержит менее одного двоеточия, он также должен быть завершён.

Error: Expected Objective-C method, but got Сообщение

Селектор может быть создан только для методов Objective-C, не для любых других процедур/функций/методов.

Error: Expected Objective-C method or constant method name

Селектор может быть создан только для методов Objective-C, при задании имени используются строковые константы или идентификатор метода Objective-C, который является видимым из текущей области видимости.

Error: No type info available for this type

Информация о типах не генерируется для некоторых типов, таких как перечисления с пропусками в их диапазоне значений (включая перечисления, нижняя граница которых отлична от нуля).

Error: Ordinal or string expression expected

The expression must be an ordinal or string type.

Error: String expression expected

The expression must be a string type.

Warning: Converting 0 to NIL

Use NIL rather than 0 when initialising a pointer.

Error: Objective-C protocol type expected, but got ”arg1”

The compiler expected a protocol type name, but found something else.

Error: The type ”arg1” is not supported for interaction with the Objective-C runtime

Objective-C makes extensive use of run time type information (RTTI). This format is defined by the maintainers of the run time and can therefore not be adapted to all possible Object Pascal types. In particular, types that depend on reference counting by the compiler (such as ansistrings and certain kinds of interfaces) cannot be used as fields of Objective-C classes, cannot be directly passed to Objective-C methods, and cannot be encoded using objc_encode.

Error: Class or objcclass type expected, but got ”arg1”

It is only possible to create class reference types of class and objcclass

Error: Objcclass type expected

The compiler expected an objcclass type

Warning: Coerced univ parameter type in procedural variable may cause crash or memory corruption: arg1 to arg2

univ parameters are implicitly compatible with all types of the same size, also in procedural variable definitions. That means that the following code is legal, because single and longint have the same size:

{$mode macpas}

Type

  TIntProc = procedure (l: univ longint);

  procedure test(s: single);

    begin

      writeln(s);

    end;

  var

    p: TIntProc;

  begin

    p:=test;

    p(4);

  end.

This code may however crash on platforms that pass integers in registers and floating point values on the stack, because then the stack will be unbalanced. Note that this warning will not flagg all potentially dangerous situations. when test returns.

Error: Type parameters of specializations of generics cannot reference the currently specialized type

Recursive specializations of generics like Type MyType = specialize MyGeneric<MyType>; are not possible.

Error: Type parameters are not allowed on non-generic class/record/object procedure or function

Type parameters are only allowed for methods of generic classes, records or objects

Error: Generic declaration of ”arg1” differs from previous declaration

Generic declaration does not match the previous declaration

Error: Helper type expected

The compiler expected a class helper type.

Error: Record type expected

The compiler expected a record type.

Error: Derived class helper must extend a subclass of ”arg1” or the class itself

If a class helper inherits from another class helper the extended class must extend either the same class as the parent class helper or a subclass of it

Error: Derived record helper must extend ”arg1”

If a record helper inherits from another record helper it must extend the same record that the parent record helper extended.

Содержание

  1. Почему выдаёт ошибку? Где я накосячила? Ошибка: unit1.pas(120,5) Fatal: Syntax error, «;» expected but «ELSE» found
  2. Fatal: Syntax error, «.» expected but «;» found
  3. 1 Answer 1
  4. Pascal Help ? 6 errors that I do not know how to fix
  5. TacticalMaestro
  6. [Паскалъ] Need Help
  7. Why does syntax error appear after running code?
  8. 1 Answer 1

Почему выдаёт ошибку? Где я накосячила? Ошибка: unit1.pas(120,5) Fatal: Syntax error, «;» expected but «ELSE» found

procedure TForm1.RadioButton1Change(Sender: TObject);
begin
if radiobutton1.checked then
begin
edit1.text := IntToStr(Bin2Dec(edit1.text));
CS := 10;
s:=edit1.text
end;
else begin
edit1.text := IntToStr(Oct2Dec(edit1.text));
CS := 10;
s:=edit1.text;

Button1.Enabled:=True;
Button2.Enabled:=True;
Button3.Enabled:=True;
Button4.Enabled:=True;
Button5.Enabled:=True;
Button6.Enabled:=True;
Button7.Enabled:=True;
Button8.Enabled:=True;
Button9.Enabled:=True;
Button10.Enabled:=True;
Button11.Enabled:=True;
Button12.Enabled:=True;
Button13.Enabled:=True;
Button15.Enabled:=True;
Button16.Enabled:=True;
Button17.Enabled:=True;
Button18.Enabled:=True;
Button14.Enabled:=True;
Button19.Enabled:=True;
Button20.Enabled:=True;
Button21.Enabled:=True;
Button22.Enabled:=True;
Button23.Enabled:=True;
end;

—-исходный кусок ————
CS := 10;
s:=edit1.text
end;
else begin
————неправильно, д. б. так ——————-
CS := 10;
s:=edit1.text;
end
else begin

З. Ы. внимательнее с синтаксисом. лучше код форматировать отступами, вроде так:
begin
begin
.
end;
end;
сразу ясно какой энд какому бегину принадлежит )))

Источник

Fatal: Syntax error, «.» expected but «;» found

1 Answer 1

The reason for this is that your begin s and end s are not balanced; disregarding the opening begin and closing end. for the program’s syntax to be correct, you should have equal numbers of each, but you have 4 begin s and 8 end s.

Obviously, your code is to compute the solutions of a quadratic equation. What I think you should do is to adjust the layout of your code so that it reflects that and then correctly the begin s and end s. In particular, your program is trying to detect whether any of a, b and d is zero and, if so, write a diagnostic message, otherwise calculate the roots by the usual formula.

Unfortunately, your begin s and end s do not reflect that. Either the whole of the block starting d := . needs to be executed or none of it does, so the else on the line before needs to be followed by a begin , as in

(You don’t say which Pascal compiler you are using, but the above fixes two points which are flagged as errors in FreePascal.

If you need more help than that, please ask in a comment.

Btw, there are some grammatical constructs in Pascal implementations where an end can appear without a matching preceding begin such as case . of . end .

Источник

Pascal Help ? 6 errors that I do not know how to fix

TacticalMaestro

Estimable

Program TypeofCreditCard;
Var
AppliName: array[1..99] of String;
SSnum: array[1..99] of Integer;
GSal: array[1..99] of Integer;
TSalD: array[1..99] of Integer;

Name, CC : String;
Rep,Exp, GS,NS,Sum,TSD , YS,SSN,i,C_Amt,PofIncome : integer ;

Begin
Writeln ( ‘Enter applicants who applied for a type of credit card’);
Readln (Rep,Exp,GS,YS,NS,Sum,TSD,SSN,CC,PofInco. ;

While ( Name <> ‘ Stop ‘ ) do
Begin
NS:= GS-TSD ;
Sum:= Exp + Rep ;
PofIncome:=(NS * 0.45);
Begin
If ( GS >4000) AND ( CC = ‘Bronze Card’ ) then
YS:= GS * 12 ;
C_Amt := YS * 0.25;
i:= i + 1;
AppliName := Name;
SSNum := SSN ;
GSal [ i]:= GS ;
TSalD := TSD ;
End ;
Begin
If (GS >= 7500) AND [CC= ‘Gold Card’] then
YS:= GS * 12 ;
C_Amt:= YS * 0.3;
i:= i + 1 ;
AppliName := Name;
SSnum:=SSN;
GSal:=GS;
TSalD:=TSD;
End;
Begin
If (GS>=10,000) AND ( CC = ‘ Platinum Card’) then
YS := GS * 12;
C_Amt: = YS * 0.4;
i:= i + 1;
A ppliName := Name;
SSNum := SSN;
GSal :=GS;
TSalD := TSD;

End if
End if
End if
End While
End.

The five errors are :
1. Error:Incompatible types: got «Boolean» expected «LongInt» — For this line : If (GS >= 7500) AND [CC= ‘Gold Card’] then

2.Error:Incompatible types: got » Set of Boolean» expected » LongInt» — for the same line (If (GS >= 7500) AND [CC= ‘Gold Card’] then )

3.Error:Incompatible types: got «single» expected «smallint» — for C_Amt := YS * 0.25 ; in Bronze Card

4.Error:Incompatible types: got «extended» expected «smallint» for C_Amt := YS * 0.3; in Gold Card

5.Fatal:syntax error , «)» expected but «,» found — (If GS >= 10000) AND [CC= ‘Platinum’] then )

Thanks for any help. I know my program is by no means perfect because I am awful at Pascal and desperately need help on fixing these things. So I am open to anything that will get this program running in Pascal. Thanks.

Источник

[Паскалъ] Need Help

Что программа должна делать(на пхп)

ЕМНИП перед else там точка с запятой не ставится.

Не, ругается на другое, и спасибо это пофиксил.

> перед else там точка с запятой не ставится.

> ругается на другое

Условия в скобки попробуй.

Перед else ; не ставится.

У readln точно такой синтаксис? (я уже запамятовал)

Условия в скобки не надо?

Операции сравнения в скобки возьми.

А теперь, дружище, запомни, что вот этот выхлоп

untitled.pas(26,7) Error: Incompatible types: got «Boolean» expected «LongInt»
untitled.pas(28,2) Fatal: Syntax error, «;» expected but «ELSE» found

должен читать ТЫ сам, а не ЛОР.

Свободно говорю на Русском, Литовском, Английском.

Свободно говорю на Английском

Error: Incompatible types: got «Boolean» expected «LongInt»

Fatal: Syntax error, «;» expected but «ELSE» found

Источник

Why does syntax error appear after running code?

presently learning how to code in pascal and vba. Assisting my daughter who is preparing for examinations next year. I am stuck on a problem concerning her present assignment. After running the code the following errors were received:

main.pas(1,2) Fatal: Syntax error, «BEGIN» expected but «identifier N» found Fatal: Compilation aborted

Tried fixing the code, but as i said I have just started learning to code.

The expected result is to choose a candidate by his ID number which would lead to his name, the number of vote available in a district and the number of votes the candidate obtained being displayed. it would then result in a calculation between the two vote counts (division) and if the percentage is greater than 20% he would receive a refund, if less than 20% he would not receive a refund. either result should be displayed.

1 Answer 1

I’m afraid that you q, as it currently stands, isn’t really suited to SO because SO is really about specific (single) programming problems, not incrementally debugging source code (see Sertac’s comment), nor providing online tutorials, which I think you probably need at this point. And I feel rather uncomfortable about posting this as an answer, because it isn’t one in the normal SO sense. However it seems to me that you could use a few pointers:

Unless you absolutely have to use the online compiler, download and use a free online one like Free Pascal, which is well supported, uses standard Pascal syntax, and I’m sure there are basic first-time tutorials available. See here to download Lazarus, which is an excellent IDE for Free Pascal (which is included in the install) and here for an introductory tutorial.

Secondly, there are structural and syntactic elements of your source-code which are definitely not standard Pascal, in particular endif and elseif . Another example is that in standard Pascal, you have to surround a string (like your Richards, etc) with single-quotes ‘ , not precede the string by a back-quote. This is very possibly the cause of your «illegal character» error

For a decent Free Pascal introductory tutorial see here and this youtube tutorial, both found by googling

«free pascal» introductory tutorial.

Fourthly, your online compiler ought to be complaining about the endif abd elseif s, the incorrectly string formatting and the fact that several of your variables are duplicated ( DV and VR used as the names of an integer variable and an array, for example as in Pascal, identifiers within the same ‘scope’ need to have unique names (the fact that I should explain what ‘scope’ means is a sign that what the q needs is a tutorial).

Источник

Status
Not open for further replies.

  • #1

Program TypeofCreditCard;
Var
AppliName: array[1..99] of String;
SSnum: array[1..99] of Integer;
GSal: array[1..99] of Integer;
TSalD: array[1..99] of Integer;

Name, CC : String;
Rep,Exp, GS,NS,Sum,TSD , YS,SSN,i,C_Amt,PofIncome : integer ;

Begin
Writeln ( ‘Enter applicants who applied for a type of credit card’);
Readln (Rep,Exp,GS,YS,NS,Sum,TSD,SSN,CC,PofInco… ;

While ( Name <> ‘ Stop ‘ ) do
Begin
NS:= GS-TSD ;
Sum:= Exp + Rep ;
PofIncome:=(NS * 0.45);
Begin
If ( GS >4000) AND ( CC = ‘Bronze Card’ ) then
YS:= GS * 12 ;
C_Amt := YS * 0.25;
i:= i + 1;
AppliName := Name;
SSNum := SSN ;
GSal [ i]:= GS ;
TSalD := TSD ;
End ;
Begin
If (GS >= 7500) AND [CC= ‘Gold Card’] then
YS:= GS * 12 ;
C_Amt:= YS * 0.3;
i:= i + 1 ;
AppliName := Name;
SSnum:=SSN;
GSal:=GS;
TSalD:=TSD;
End;
Begin
If (GS>=10,000) AND ( CC = ‘ Platinum Card’) then
YS := GS * 12;
C_Amt: = YS * 0.4;
i:= i + 1;
A ppliName := Name;
SSNum := SSN;
GSal :=GS;
TSalD := TSD;

End if
End if
End if
End While
End.

The five errors are :
1. Error:Incompatible types: got «Boolean» expected «LongInt» — For this line : If (GS >= 7500) AND [CC= ‘Gold Card’] then

2.Error:Incompatible types: got » Set of Boolean» expected » LongInt» — for the same line (If (GS >= 7500) AND [CC= ‘Gold Card’] then )

3.Error:Incompatible types: got «single» expected «smallint» — for C_Amt := YS * 0.25 ; in Bronze Card

4.Error:Incompatible types: got «extended» expected «smallint» for C_Amt := YS * 0.3; in Gold Card

5.Fatal:syntax error , «)» expected but «,» found — (If GS >= 10000) AND [CC= ‘Platinum’] then )

Thanks for any help. I know my program is by no means perfect because I am awful at Pascal and desperately need help on fixing these things. So I am open to anything that will get this program running in Pascal. Thanks.

Hawkeye22



Feb 10, 2006



713



0



19,460

95


  • #2

1 & 2. Square brackets should be parenthesis:
This: If (GS >= 7500) AND [CC= ‘Gold Card’] then
Should be this: If (GS >= 7500) AND (CC= ‘Gold Card’) then

3 & 4:
You have C_Amt and YS declared as integer yet you are multiplying by a real.

5: there should be no parenthesis at the end of that line.

Your code is hard to read. try indenting where needed. if it was already indented before you copied/pasted, then use the [code ] bbcodes in order to keep the formatting.

Hawkeye22



Feb 10, 2006



713



0



19,460

95


  • #2

1 & 2. Square brackets should be parenthesis:
This: If (GS >= 7500) AND [CC= ‘Gold Card’] then
Should be this: If (GS >= 7500) AND (CC= ‘Gold Card’) then

3 & 4:
You have C_Amt and YS declared as integer yet you are multiplying by a real.

5: there should be no parenthesis at the end of that line.

Your code is hard to read. try indenting where needed. if it was already indented before you copied/pasted, then use the [code ] bbcodes in order to keep the formatting.

Onus



Jan 27, 2006



724



0



19,210

64


  • #3

Well for one thing, the «[» and «]» may not be used in place of parentheses «(» and «)» in boolean expressions to be evaluated. Second, if you want to assign the integer portion of a real number to an integer variable, you need to use a function like TRUNC, as in «integer_var := TRUNC(real_expression);»



Jan 13, 2011



4,165



4



35,260

1,357


  • #4

This is how your program looks when enclosed in [ code ] and [ / code ] tags:

Program TypeofCreditCard; 
Var 
    AppliName: array[1..99] of String; 
    SSnum: array[1..99] of Integer; 
    GSal: array[1..99] of Integer; 
    TSalD: array[1..99] of Integer; 

    Name, CC : String; 
    Rep,Exp, GS,NS,Sum,TSD , YS,SSN,i,C_Amt,PofIncome : integer ; 

Begin 
    Writeln ( 'Enter applicants who applied for a type of credit card'); 
    Readln (Rep,Exp,GS,YS,NS,Sum,TSD,SSN,CC,PofInco... ; 

    While ( Name <> ' Stop ' ) do 
    Begin 
        NS:= GS-TSD ; 
        Sum:= Exp + Rep ; 
        PofIncome:=(NS * 0.45); 
        Begin 
            If ( GS >4000) AND ( CC = 'Bronze Card' ) then 
                YS:= GS * 12 ; 
            C_Amt := YS * 0.25; 
            i:= i + 1; 
            AppliName := Name; 
            SSNum := SSN ; 
            GSal [ i]:= GS ; 
            TSalD := TSD ; 
        End ; 
        Begin 
            If (GS >= 7500) AND [CC= 'Gold Card'] then 
                YS:= GS * 12 ; 
            C_Amt:= YS * 0.3; 
            i:= i + 1 ; 
            AppliName := Name; 
            SSnum:=SSN; 
            GSal:=GS; 
            TSalD:=TSD; 
        End; 
        Begin 
            If (GS>=10,000) AND ( CC = ' Platinum Card') then 
                YS := GS * 12; 
            C_Amt: = YS * 0.4; 
            i:= i + 1; 
            AppliName := Name; 
            SSNum := SSN; 
            GSal :=GS; 
            TSalD := TSD; 
        End if 
        End if 
        End if 
    End While 
End.



Jan 13, 2011



4,165



4



35,260

1,357


  • #5

(sorry for double-post, it will be easier)…

Appart from the errore already discussed, there are some more:
— there are not «end if» and «end while» operators in Pascal (OK, at least in the popular ones);
— your ReadLn statement probably won’t work — string variables will get empty values. Split it on several Write / ReadLn statements
— you have several arrays, but assignment statements are missing [Index] part of the array, e.g. AppliName := Name;
— you are not checking if one will enter more that 100 applicants

  • #6

Thank you everyone. I will give you all an update when i incorporate all of these corrections.

By the way, I am using Free IDE Pascal .

Onus



Jan 27, 2006



724



0



19,210

64


  • #7

I used to use Turbo Pascal. Ah, those were the days…

  • #8

I’m down to 2 errors now and I am pleased but I just really need it to run.
This is the error — Fatal:Syntax Error, «;» expected but «identifier Writeln found — Source of error- Writeln ( ‘Enter applicants who applied for a type of credit card’);

Is there some sort of documentation about what each error means??I want to learn.

Ijack



Jul 30, 2008



1,035



0



20,360

113


  • #9

The message means exactly what it says. The compiler was expecting to find «;» but instead it found «Writeln». Normally this means the semicolon is missing from the line before the one listed but your program, as you list it, has no statement before that line. Have you added something since?

  • #10

The message means exactly what it says. The compiler was expecting to find «;» but instead it found «Writeln». Normally this means the semicolon is missing from the line before the one listed but your program, as you list it, has no statement before that line. Have you added something since?

I’ve done nothing but do the changes I’ve been told to made.



Jan 13, 2011



4,165



4



35,260

1,357


  • #11

@Tactical, post your complete code, here or on e.g. PasteBin. If you post it here, encclose it in «code» tags
that is, (omit ‘_’ from example below)
[_code_]
Program something;

end.
[_/code_]

Ijack



Jul 30, 2008



1,035



0



20,360

113


  • #13

You have deleted the «Begin» between the variable declarations and the program statements. Reinstate it (just before the offending line) and try again.

  • #14

You have deleted the «Begin» between the variable declarations and the program statements. Reinstate it (just before the offending line) and try again.

I inserted that beginning then one more error came up and it said
Fatal syntax error, «;’ expected but » BEGIN» found



Jan 13, 2011



4,165



4



35,260

1,357


  • #15

@Tactical — it would be helpful if you mention what compiler you’re using, and (when errors happen) — at what line.

On your program:
— Put a «Begin» before first «WriteLn»;
— Put «I := 0» before «while» statement
— change «while» to check that I is less than 100
— change internal «If» to check for «Name <> ‘Stop'»
— Remove last two «End;» before «End.»;

Probably there are more… Change your program, re-post it on PasteBin for further help

  • #16

So i followed through and continued to attempt to run the program and eventually after trying to follow and fix every error , I think it started running but i don’t understand because its been more than 5 hours now that it has said that the PASCAL file is now running but i can not type anything in the black screen and it can not be closed down.Additionally, because I didn’t know it would run after i corrected the last error, this means that I have not saved the most recent version of the PASCAL yet. The problem with that is for my assignment it says » You have to show evidence that your program ran (a print screen after it compiled. Print screen of some data that you entered and a print screen of the output) «

Will it ever run or come off of this screen that it seems to be stuck on?



Jan 13, 2011



4,165



4



35,260

1,357


  • #17

@Tactical — for God’s sake, what version of Pascal are you using?
Try pressing <Ctrl>-<Break>, or <Ctrl>-C, to terminate your program. If you have a debugger in your environment, you can try to terminate your program from there as well.

And since we don’t know how your program looks now, noone can tell what will come out of it ;)

Ijack



Jul 30, 2008



1,035



0



20,360

113


  • #18

The last version of the program that you listed had an infinite loop in it. You never change the value of «Name» inside the «While» loop. This is why the program keeps running.

As the previous poster said, just break into the program. How you do that depends upon your environment.

Status
Not open for further replies.
Thread starter Similar threads Forum Replies Date

B

Solved! Apple Community Reload Error Apps General Discussion 4 Jun 14, 2022

K

Question cache deleted in error Apps General Discussion 1 Apr 25, 2022

xarzu

Question How do I update my computer because I have an error? Apps General Discussion 0 Apr 12, 2022

C

Question Photoshop Elements 2021 error codes 81 and 501 won’t allow installation? How to fix. Apps General Discussion 1 May 5, 2021

aymen9309

Question i need help in a simple pascal program Apps General Discussion 1 Jun 18, 2020

David___Only

Question How to fix“ ERROR-invalid argument/option — ‘Live’ ” in this code? Apps General Discussion 0 Jul 21, 2019

KloneCSGO

Question PUBG Lite launcher error Apps General Discussion 2 Jul 1, 2019

reble

Question Win dos shell syntax error Apps General Discussion 2 Apr 11, 2019

I

Solved! Getting error 502 Bad Gateway, is it proxy or website itself Apps General Discussion 5 Jan 23, 2019

U

ASCII in Pascal programming Apps General Discussion 4 Dec 13, 2015

A

Pascal homework help Apps General Discussion 2 Mar 7, 2015

shiftyape

need help with pascal programming Apps General Discussion 4 Feb 22, 2014

shiftyape

why wont this pascal program work? idk Apps General Discussion 18 Dec 13, 2013

shiftyape

need help with this pascal programming. Apps General Discussion 3 Dec 13, 2013

shiftyape

why doesnt this pascal program work? Apps General Discussion 1 Dec 7, 2013

shiftyape

need help with pascal programming? Apps General Discussion 2 Dec 7, 2013

shiftyape

i need help fixing this pascal program Apps General Discussion 13 Dec 5, 2013

L

Which programming languages will I need to learn as an actuary? Apps General Discussion 2 Dec 12, 2012

M

** A CHALLENGE ** UCSD P-sytem Pascal ** Apps General Discussion 7 Oct 15, 2010

P

pascal quation.. Apps General Discussion 7 Nov 13, 2008

  • Advertising
  • Cookies Policies
  • Privacy
  • Term & Conditions
  • Topics

Arefev596

1 / 1 / 0

Регистрация: 15.01.2021

Сообщений: 29

1

03.05.2021, 21:46. Показов 1626. Ответов 2

Метки нет (Все метки)


Крайне благодарен буду тому,кто даст мне подзатыльник и объяснит,что и где не так.Спасибо!)
Пытаюсь написать код шифрования Диффи-Хеллмана,но не получается,ошибки…
Само задание: Написать программу, использующую алгоритм шифрования данных для преобразования исходного текста.
main.pas(7,33) Error: Incompatible types: got «Extended» expected «Int64»
main.pas(21,18) Error: Incompatible type for arg no. 1: Got «Real», expected «SmallInt»
main.pas(24,18) Error: Incompatible type for arg no. 1: Got «Real», expected «SmallInt»
main.pas(25,11) Error: Incompatible types: got «untyped» expected «SmallInt»
main.pas(26,11) Error: Incompatible types: got «untyped» expected «SmallInt»

Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
procedure search (a, b : Integer; P:extended);
label return;
begin
    if (b)=1 then 
        goto return
    else
        writeln(exp(b*LN(a) mod P));
end;
 
 
Var P, G: Real; 
    x, y, a, b, ka, kb:Integer;
 
begin 
    writeln ('Введите первое общее публичное число ');
    readln(P);
    writeln ('Введите второе общее публичное число ');
    readln(G);
    writeln ('Введите выбранный закрытый ключ для 1-го пользователя ');
    readln(a);
    x := search(G, a, P);
    writeln ('Введите выбранный закрытый ключ для 2-го пользователя ');
    readln(b);
    y := search(G, b, P); 
    ka := search(y, a, P);
    kb := search(x, b, P);
    writeln ('Секретный ключ для 1 : ', ka);
    writeln ('Секретный ключ для 2 : ', kb);
    break;
end.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

03.05.2021, 21:46

Ответы с готовыми решениями:

Error: Incompatible types: got «Extended» expected «SmallInt»
Задание. Написать программу решения задачи, используя функции: в основной функции вычислить с…

Error: Incompatible types: got «Boolean» expected «Int64»
Здравствуйте, возникла ошибка в программе project1.lpr(43,6) Error: Incompatible types: got…

Ошибка .pas(15,9) Fatal: Syntax error, «;» expected but «ELSE» found
На паскале пишу код ровно один день,не понимаю,почему ругается…Буду благодарен за…

Составить фразу «текстовый редактор» из слов «тесто», «редакция», «мотор», «который»
1) Составить фразу &quot;текстовый редактор&quot; из слов &quot;тесто&quot;, &quot;редакция&quot;, &quot;мотор&quot;, &quot;который&quot;.

2

Модератор

Эксперт Pascal/DelphiЭксперт NIX

7502 / 4370 / 2776

Регистрация: 22.11.2013

Сообщений: 12,506

Записей в блоге: 1

04.05.2021, 09:35

2

Цитата
Сообщение от Arefev596
Посмотреть сообщение

объяснит,что и где не так

Нужно читать сообщения компилятора, там написано где не так (в скобках) и что именно не так. Перечитайте, расскажите, что осталось непонятным.

Error — ошибка
Incompatible types — несовместимые типы
Got «нечто» expected «другое» — получено «нечто», ожидалось «другое»

Из написанного неявно и ненаписанного:
1) procedure не возвращают значений по своему имени вызова.
2) break прерывает цикл, в других случаях бесполезен.



1



1 / 1 / 0

Регистрация: 15.01.2021

Сообщений: 29

06.05.2021, 10:22

 [ТС]

3

Понял,спасибо!



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

06.05.2021, 10:22

Помогаю со студенческими работами здесь

Составить фразу «письменный стол» из слов «тесненный», «полка», «речь», «миф».
1) Составить фразу &quot;письменный стол&quot; из слов &quot;тесненный&quot;, &quot;полка&quot;, &quot;речь&quot;, &quot;миф&quot;.
2) Вывести…

Составить фразу «программное обеспечение» из слов «программист», «оборот», «анчоус», «измерение»
Составить фразу &quot;программное обеспечение&quot; из слов &quot;программист&quot;, &quot;оборот&quot;, &quot;анчоус&quot;,…

Заменить символы «1», «2», «3» словами «один», «два», «три»
Дана строка символов. Заменить символы &quot;1&quot;, &quot;2&quot;, &quot;3&quot; словами &quot;один&quot;, &quot;два&quot;, &quot;три&quot;. Оформить в…

Составить програму, которая б после каждой буквы «е» в данном слове дописывала букву «о» и меняла словосочетание «да» на «нет»
Составить програму, которая б после каждой буквы &quot;е&quot; в данном слове дописывала букву &quot;о&quot; и меняла…

Построить последовательно применяя методы «отобразить», «сдвинуть», «изменить размеры», «спрятать» иерархии обьектов
построить последовательно применяя методы &quot;отобразить&quot;, &quot;сдвинуть&quot;, &quot;изменить размеры&quot;,…

Проверить слово «Дом» и содержит ли оно буквы: «а» , «б» ,»о»,»д»
программа должна проверить слово &quot;Дом&quot; и содержит ли оно буквы: &quot;а&quot; , &quot;б&quot;…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

3

When I compile your code under FreePascal, I get:

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                                                       

so it looks like a conflict between integer and floating point types. When I switch all variables other than p to be of type real:

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

then it compiles fine.

And, when executing that with known values:

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

I see:

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

That was done with some slight modifications to the program to make the output more readable but the bulk of the code (specifically the calculations) was left untouched.

Topic: [SOLVED] Incompatible types  (Read 34236 times)

function SomeFunc(): Integer;
var
  i: Integer;

begin
  i:= 1440 / 2;
end; 

Error: unit1.pas(49,12) Error: Incompatible types: got «Extended» expected «LongInt»

help

« Last Edit: November 19, 2012, 05:40:59 pm by deepaak99 »


Logged

Holiday season is online now. :-)


You are assigning a real value to an integer variable. Change «i: integer» to «i: double» and you are fine.

« Last Edit: November 19, 2012, 11:13:29 am by JD »


Logged

Windows (10) — Lazarus 2.1/FPC 3.2 (svn 64160 built using fpcupdeluxe),
Linux Mint — Lazarus 2.1/FPC 3.2 (svn 64380 built using fpcupdeluxe),
Delphi

Indy 10.6 series; mORMot; Zeos 7.3; SQLite, Firebird, PostgreSQL & MariaDB; VirtualTreeView 5.5.3 R1


/ is a floating point division
div is an integer division


Logged



Logged

Dear Confucius you said {A picture is worth a thousand words}
I say {a good example is worth a thousand words}



Logged

Lazarus Trunk / fpc 2.6.2 / Win32


or

function SomeFunc(): Integer;
var
  i: Integer;

begin
  i:= round(1440 / 2);
end; 


or

function SomeFunc(): Integer;
var
  i: Integer;

begin
  i:= trunc(1440 / 2);
end; 

« Last Edit: November 19, 2012, 01:02:43 pm by Fred vS »


Logged


orfunction SomeFunc(): Integer;
var
  i: Integer;

begin
  i:= round(1440 / 2);
end; 


orfunction SomeFunc(): Integer;
var
  i: Integer;

begin
  i:= trunc(1440 / 2);
end; 

i:= 1440 Div 2

/ is a floating point division
div is an integer division

Thank you. div was new for me, as in c «/» is used for division, round() and trunk() is also a treat  :)


Logged

Holiday season is online now. :-)


If DIV was new for you, you should also look at MOD.


Logged

Lazarus Trunk / fpc 2.6.2 / Win32


Модератор: Модераторы

Error: Incompatible types

нужна помощь с фри паскалем.
при попытке установить функцию для изменения размеров (glut) вылазит еррор.
как обьявляю функцию:

Код: Выделить всё
procedure ReSizeGLScene(Width, Height: smallint); cdecl;

назначаю:

Код: Выделить всё
glutReshapeFunc(@ReSizeGLScene);

компилятор говорит:

Код: Выделить всё
Error: Incompatible types: got "<address of procedure(SmallInt,SmallInt);CDecl>" expected "<procedure variable type of procedure(LongInt,LongInt);CDecl>"
Lincor
незнакомец
 
Сообщения: 4
Зарегистрирован: 02.07.2013 01:13:41

Re: Help!

Сообщение Vadim » 02.07.2013 03:08:56

Ну так сделайте, что Вам говорит компилятор: «ожидается процедурная переменная».

Vadim
долгожитель
 
Сообщения: 4112
Зарегистрирован: 05.10.2006 08:52:59
Откуда: Красноярск

Re: Help!

Сообщение bormant » 03.07.2013 09:20:06

У вас
procedure(smallint, smallint); cdecl;
а ожидается
procedure(longint, longint); cdecl;

Аватара пользователя
bormant
постоялец
 
Сообщения: 402
Зарегистрирован: 21.03.2012 11:26:01

Re: Help!

Сообщение Lincor » 03.07.2013 17:16:05

ой, я думал, наоборот. пойду учить английский
спасибо!

Lincor
незнакомец
 
Сообщения: 4
Зарегистрирован: 02.07.2013 01:13:41


Вернуться в Free Pascal Compiler

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 7

Формулировка задачи:

Задание.

Написать программу решения задачи, используя функции: в основной функции вычислить с помощью генератора случайных чисел 10 элементов массива, во вспомогательной — вычислить скалярную величину.
Проблема в том что я не смог сделать правильно задание на Паскале.

Программа нормально работает

На паскале:

как это исправить ?

Код к задаче: «Error: Incompatible types: got «Extended» expected «SmallInt»»

textual

const
  n = 10;
type
  mas=array[1..n] of integer;
 
function F(X:mas):real;
  function L(X:mas):real;
  var
    Pr : real;
    i : integer;
  begin
    Pr:=1;
    for i:=1 to n do
      Pr:=(1+abs(X[i]));
    L:=Pr
  end;
 
var
  i:integer;
  sum : real;
begin
  sum:=0;
  for i:=1 to n do
    sum:=(sqr(X[i])-2*X[i])/L(x);
  F:=sum
end;
 
var
  X:mas;
  i:integer;
  g:real;
begin
  writeln('Massiv X');
  randomize;
  for i:=1 to n do
  begin
    X[i]:=random(20)-10;
    write(X[i]:3);
  end;
  writeln;
  g:=F(X);
  writeln('g=',g:0:2);
end.

Полезно ли:

15   голосов , оценка 4.133 из 5

Pl0 Compiler

Top-Level Error Report:

  1. Errors occurred during parsing.
  2. Extra characters in source text.
  3. Errors occurred during semantic analysing.

ERROR When Parsing:

  1. expected character ‘c’. (single symbol)
  2. expected literal string «string». (keywords)
  3. invalid characters to construct identifier.
  4. an identifier can’t be as same as anyone of the keywords.
  5. expected integer or char as the primitive data type. (parse primitive type)

ERROR Recovery (skip while invalid)

  1. parse identifier

    skip all characters until get a valid identifier.

ERROR When Semantic Analysing (Type Checking):

  1. redefinition of «a»
  2. use of undeclared identifier «a»
  3. use an array identifier «a» as a factor.
  4. expected an array identifier.
  5. expected an non-array identifier.
  6. expected an valid expression as the array index.
  7. expected an valid expression as the condition expression.
  8. compare two expressions with different types.
  9. do +/- operation on two factors with different types.
  10. do *// operation on two terms with different types.
  11. duplicate identifier «F» (when there is a variable with the same name of it’s container function or procedure)
  12. overloaded identifier «F» isn’t a function (when there is a function or procedure with the same name of it’s container function or procedure, or define a function or procedure when there already is a variable or constant with the same name.)

Error: Incompatible types: got «SmallInt» expected «Char»

ABOUT TYPE CAST:

  1. char can cast to integer implicitly.
  2. integer can’t cast to char.
  3. array of char and array integer can do no type casting.
  4. const value can do no type casting.

ABOUT x86 Code Generate

  1. 寄存器分配
  2. 寻址:根据深度,从ebp逐级向上找。
  3. 在对引用类型的变量分配寄存器时,不能分配 eax 寄存器。(eax寄存器要用于引用变量的寻址过程)

一个关于中间代码的问题:先将函数嵌套拆分(flatten)

对于for循环的汇编代码生成:在循环开始处和循环结束处都将循环变量加载至 eax 寄存器中。(认为循环变量是活跃的)

调用C库函数scanf和printf之前需要保存eax, ebx, ecx寄存器。(eax会被用作这两个函数的返回值寄存器)
遵守x86 ABI的调用约定

对于分支,如果一个分支内有临时变量溢出到栈上,另一个分支内没有,栈的平衡就会被破坏。一个分支内产生的临时变量无法到达分支之后的基本块中。

四元式:

  1. = target source

  2. []= array index source

  3. =[] target array index

  4. loadret

  5. call func/proc {args} [return]

  6. read target

  7. write_s string label

  8. write_e value

    • c a b
    • c a b
    • c a b
  9. / c a b

  10. % c a b

  11. cmp a b

  12. label label_no

  13. goto label_no

  14. def // 定义循环语句的结束处的临时变量变量和case语句的条件表达式临时变量,在划分基本块时,def 语句被整合到函数或者过程头部。

优化:

  1. 划分基本块:在四元式中,每个基本块对应一个label,用label编号作为基本块的编号。对于函数头声明,该块编号为 0
  2. 将函数调用也作为划分基本块的边界依据。

** 有三种临时变量的作用范围会跨越基本块:

  • for 循环语句,作为结束条件的临时变量
  • case 语句,作为condition的临时变量。
  • 会与函数的返回结果做运算的临时变量。(解决:在维护栈平衡级别,合并函数调用的基本块)
  1. 按照pascal的语义,循环语句中,无论循环体是否执行,执行多少次,在循环结束后,循环变量的值都等于 end 的值。(解决方案:在循环末尾生成显式赋值语句)

Понравилась статья? Поделить с друзьями:
  • Error incompatible types got real expected smallint
  • Error incompatible types got extended expected smallint
  • Error incompatible types got extended expected longint
  • Error incompatible types got double expected smallint
  • Error incompatible types got double expected longint