Fatal syntax error expected but procedure found

Ошибка "Fatal: Syntax error, ";" expected but "." found" Lazarus Решение и ответ на вопрос 2185902

stkapler

0 / 0 / 0

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

Сообщений: 19

1

07.02.2018, 04:52. Показов 22831. Ответов 14

Метки delphi, lazarus, pascal (Все метки)


звучит задание: создай программу, в которой можно преподнести введенное пользователем число к указанному степеню.

покапавшись на всяких форумах и тп, написал код. вроде бы все ок. но при компиляции выдает ошибку в 41 строке unit1.pas(42,17) Fatal: Syntax error, «;» expected but «.» found

ниже код:

Delphi
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
unit Unit1;
 
{$mode objfpc}{$H+}
 
interface
 
uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;
 
type
 
  { TForm1 }
 
  TForm1 = class(TForm)
    Button1: TButton;
    E1: TEdit;
    E2: TEdit;
    Label1: TLabel;
    Label2: TLabel;
    procedure Button1Click(Sender: TObject);
  private
    { private declarations }
  public
    { public declarations }
  end;
 
var
  Form1: TForm1;
  x, n, y: extended;
 
implementation
              function Power(const Base, Exponent: Extended): Extended;
{$R *.lfm}
 
{ TForm1 }
 
procedure TForm1.Button1Click(Sender: TObject);
begin;
   x:=strtofloat(e1.text);
   n:=strtofloat(e2.text);
   y:=Power(n, x);
   label2.caption:=floattostrf(s, ffFixed, 5,2);
end;
 
end.

ps. уже сам нашел несколько ошибок, но все равно проблема осталась

Добавлено через 8 минут
*СТРОКА 37, А НЕ 41

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



0



Programming

Эксперт

94731 / 64177 / 26122

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

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

07.02.2018, 04:52

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

Ошибка «project1.lpr(35,0) Fatal: Syntax error, «BEGIN» expected but «end of file» found»
type
tarray= array of integer;
var
a:tarray;
m,s,k:integer;
procedure…

Ошибка: project1.lpr(1,1) Fatal: Syntax error, «BEGIN» expected but «end of file» found
project1.lpr(1,1) Fatal: Syntax error, "BEGIN" expected but "end of file" found
выдает эту ошибку…

Ошибка: Fatal: Syntax error, «;» expected but «identifier Mas» found.
Где здесь синтаксическая ошибка( "mas:=A2;" )?

procedure TForm1.Button1Click(Sender: TObject);

Ошибка Fatal: Syntax error, «;» expected but «is» found
Не могу нигде прописать часть кода вот эт type tproc = procedure is…

14

Джоуи

1073 / 635 / 240

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

Сообщений: 3,546

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

07.02.2018, 05:48

2

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

implementation function Power(const Base, Exponent: Extended): Extended;

Директива implementation означает раздел реализации, а не описания. Вы не реализовали функцию Power, а просто ее описали (нету begin end). Кстати, переименуйте как-нибудь, а то функция Power уже есть в паскале



0



Модератор

8257 / 5480 / 2249

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

Сообщений: 23,584

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

07.02.2018, 06:04

3

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

НЕ ЗНАЮ ЧТО ДЕЛАТЬ!

 Комментарий модератора 
1. Создавать темы в нужном разделе
2. Создавать темы с осмысленным названием
3. Не дублировать свои темы!!!

Это официальное предупреждение: Ваши действия — это нарушение правил форума, а именно пп 4.2, 5.4 и 5.5

3. В секции uses подключить модуль Math
4. Удалить к чертовой матери строку 32
5. В строке 42 заменить переменную внутри FloatToStr(…) Вы присвоили результат возведения в степень в переменную Y, а там у Вас какая-то, не пойми откуда взявшаяся, S…



0



stkapler

0 / 0 / 0

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

Сообщений: 19

07.02.2018, 12:22

 [ТС]

4

сделал все как вы сказали
но теперь выдает ошибку в сроке 39 и 40

unit1.pas(39,25) Error: Incompatible type for arg no. 1: Got «TTranslateString», expected «Int64»

unit1.pas(39,25) Error: Incompatible type for arg no. 1: Got «TTranslateString», expected «Int64»

сами строки

Pascal
1
2
   x:=FloatToStr(E1.Text);
   n:=FloatToStr(E2.Text);

у меня есть готовый ответ на это задание, даже 2. но все таки хочу найти решение самостоятельно, пусть даже при помощи форумчан)



0



Модератор

8257 / 5480 / 2249

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

Сообщений: 23,584

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

07.02.2018, 12:35

5

stkapler, Вы строку переводите в число, поэтому функция StrToFloat()

Добавлено через 7 минут
В стартовом посте все правильно ведь было написано!



0



0 / 0 / 0

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

Сообщений: 19

07.02.2018, 12:36

 [ТС]

6

все хорошо, спасибо! проект компилируется и запускается

НО!! при вводе чисел и после нажатия кнопки — ничего не происходит. а должен быть результат

visible включен. шрифт норм, цвет отличный от фона. ничего не понимаю



0



Модератор

8257 / 5480 / 2249

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

Сообщений: 23,584

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

07.02.2018, 12:41

7

А Вы этот обработчик создавали, или так просто написали?



0



0 / 0 / 0

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

Сообщений: 19

07.02.2018, 12:43

 [ТС]

8

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



0



Модератор

8257 / 5480 / 2249

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

Сообщений: 23,584

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

07.02.2018, 14:48

9

Лучший ответ Сообщение было отмечено ZX Spectrum-128 как решение

Решение

Не по теме:

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

А Вы этот обработчик создавали

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

нет, не создавал но в планах для красивого оформления программы это есть

:scratch:

stkapler, возьмите любую книжку по самым-самым азам создания программ в среде Delphi/Lazarus и обязательно прочтите ее… Ну или программирование бросайте прямо сейчас…
Все, что от Вас требовалось — это положить на форму кнопку, сделать на этой кнопке двойной клик и в получившейся заготовке обработчика события написать код.



0



0 / 0 / 0

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

Сообщений: 19

07.02.2018, 19:11

 [ТС]

10

спасибо, теперь все ок!
мне тут пол года учиться осталось, до сдам эти проекты — и буду гулять
вообще не пойму, зачем в 2018 дают учить паскаль
но за помощь — огромное спасибо!



0



Hretgir

07.02.2018, 20:01

Не по теме:

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

зачем в 2018 дают учить паскаль

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



0



0 / 0 / 0

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

Сообщений: 19

07.02.2018, 20:08

 [ТС]

12

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



0



Hretgir

07.02.2018, 20:37

Не по теме:

а что-бы вы хотели учить в 2018? просто интересно…
вот я-бы хотел учить нейросети, а получается что по факту мне нужен паскаль, на настоящий момент.
хотя можете не отвечать, я только мешаю.



0



stkapler

07.02.2018, 20:58

 [ТС]

Не по теме:

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



0



Cyborg Drone

08.02.2018, 09:25


    Ошибка «Fatal: Syntax error, «;» expected but «.» found»

Не по теме:

Да не спорьте. Не нужно знать язык программирования — значит, не нужно. Личное дело каждого. С другой стороны, те, кто всерьёз занимается программированием, как правило, знает несколько языков программирования, и выучить ещё один, как правило, никакая не проблема.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

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

08.02.2018, 09:25

Fatal: Syntax error, «BEGIN» expected but «end of file» found
Доброго времени суток! Вот простой код, который, по идее, находит корни квадратного уравнения….

Unit1.pas(41,5) Fatal: Syntax error, «;» expected but «identifier Y» found
Привет всем.Сделал программу,вроде как должна работать,не пойму в чем проблема(программа вся…

Fatal: Syntax error, «BEGIN» expected but «identifier BITMAP» found
Добрый день! пишу программу по методичке, выдает вот такие ошибки:
unit1.pas(78,1) Fatal: Syntax…

Unit1.pas(66,4) Fatal: Syntax error, «;» expected but «.» found
unit Unit1;

{$mode objfpc}{$H+}

interface

uses
Classes, SysUtils, FileUtil, Forms,…

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

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

15

Topic: problem with Fatal: Syntax error, «;» expected but «:» found  (Read 5270 times)

Hello, I am a beginner in Lazarus and the Pascal language.
my problem is that every time I try to run my program it gives me this error: Fatal: syntax error, «;» expected but found.
in case there is any doubt this is the program.
program division;
var
a,b,c:double;
begin
writeln(‘extra division’);
writeln(‘ingresa el divisor’);
readln(a);
writeln(‘ingresa el dividendo’);
readln(b);
if (b=0) then
begin
writeln(‘math error’);
readln;
end
else
begin
c:a/b;
writeln(‘el resultado de la division es’,c:4:2);
readln;
end;

I would be very grateful to you if you could help me solve this problem.


Logged



Logged


HOMEWORK ???

  1. PROGRAM Division;

  2. VAR dDividend,dDivisor,dQuotient:Double;

  3. BEGIN

  4. Writeln(‘extra division’);

  5. Writeln(‘ingresa el dividendo’);

  6. Readln(dDividend);

  7. Writeln(‘ingresa el divisor’);

  8. Readln(dDivisor);

  9. If (dDivisor = 0)

  10. Then

  11. Begin

  12. Writeln(‘math error’);

  13. Readln;

  14. End

  15. Else

  16. Begin

  17.     dQuotient:= dDividend/dDivisor;

  18. Writeln(‘el resultado de la division es:  ‘,dQuotient:4:2);

  19. Readln;

  20. END;

  21. END.


Logged

Windows 7 Pro (x64 Sp1) & Windows XP Pro (x86 Sp3).



Logged


Hello, I am a beginner in Lazarus and the Pascal language.
my problem is that every time I try to run my program it gives me this error: Fatal: syntax error, «;» expected but found.
in case there is any doubt this is the program.
program division;
var
a,b,c:double;
begin
writeln(‘extra division’);
writeln(‘ingresa el divisor’);
readln(a);
writeln(‘ingresa el dividendo’);
readln(b);
if (b=0) then
begin
writeln(‘math error’);
readln;
end
else
begin
c:a/b;
writeln(‘el resultado de la division es’,c:4:2);
readln;
end;

I would be very grateful to you if you could help me solve this problem.


Logged

One System to rule them all, One Code to find them,
One IDE to bring them all, and to the Framework bind them,
in the Land of Redmond, where the Windows lie
———————————————————————
Code is like a joke: If you have to explain it, it’s bad


This line:

  1. c:a/b;

Needs to be changed to this:

  1. c := a/b;

Also, you need to add the following at the bottom of the file to close your 1st ‘begin’ and the unit as a whole:

  1. end.

So, the entire code should look like this:

  1. program division;

  2. var

  3.   a, b, c : double;

  4. begin

  5. WriteLn(‘extra division’);

  6. WriteLn(‘ingresa el divisor’);

  7. ReadLn(a);

  8. WriteLn(‘ingresa el dividendo’);

  9. ReadLn(b);

  10. if (b=0) then

  11. begin

  12. WriteLn(‘math error’);

  13. ReadLn;

  14. end

  15. else

  16. begin

  17.     c := a / b; // <— CHANGED!!!

  18. WriteLn(‘el resultado de la division es’, c:4:2);

  19. ReadLn;

  20. end;

  21. end. // <— ADDED!!!

« Last Edit: June 19, 2020, 08:31:39 pm by Remy Lebeau »


Logged


@Remy Lebeau: almost … one is missing …  :P
You don’t get the flower pot !


Logged

Windows 7 Pro (x64 Sp1) & Windows XP Pro (x86 Sp3).


@Remy Lebeau: almost … one is missing …  :P

Which one?  I don’t see anything missing in the code I posted.


Logged


I don’t see anything missing in the code I posted.

Correct, nothing is missing, but the «WriteLn» order is not optimal…

Divisor (a), Dividend (b), Check b = 0 (Dividend?), Divisor/Dividend ?

In my world you have to do it like this:
Dividend / Divisor = Quotient   :)

As I said, you don’t get the flower pot …  :D


Logged

Windows 7 Pro (x64 Sp1) & Windows XP Pro (x86 Sp3).


Hi!

Dont battle about the poor dividende.

We could teach him the way the C boys do it:
Division by zero is no error. Never.

SetExceptionMask([exZeroDivide, exInvalidOp, exDenormalized, exOverflow, exUnderflow, exPrecision]);
….

You dont have to ask for dividing by zero anymore.
The price you have to pay:
Incorrect results and a system crash every now and then.
We all know that from Windows.

Winni


Logged


Dont battle about the poor dividende.

We could teach him the way the C boys do it:
Division by zero is no error. Never.

I think RAW is referring just to the terminology in the WriteLn’s: Remy’s code asks for the divisor when he means the dividend and viceversa. Just a small oversight ;D


Logged

Turbo Pascal 3 CP/M — Amstrad PCW 8256 (512 KB !!!) :P
Lazarus/FPC 2.0.8/3.0.4 & 2.0.12/3.2.0 — 32/64 bits on:
(K|L|X)Ubuntu 12..18, Windows XP, 7, 10 and various DOSes.


…code asks for the divisor when he means the dividend and viceversa…

@lucamar: the flowers are all yours …  :)

by the way: no battle at all, just a little hint that the code isn’t optimal …  :)


Logged

Windows 7 Pro (x64 Sp1) & Windows XP Pro (x86 Sp3).


I think RAW is referring just to the terminology in the WriteLn’s: Remy’s code asks for the divisor when he means the dividend and viceversa. Just a small oversight ;D

It is not MY code, it is the OP’s code.  I just fixed the syntax errors, not the logic errors.


Logged


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

Ошибка Fatal: Syntax error, «;» expected

Доброго времени суток, препод дала задание, но при компиляции программа выдает ошибку «cloud.pas(51,12) Fatal: Syntax error, «;» expected but «identifier TFORM1″ found»
В код никакой отсебятины не добавлялось, полное копирование из задания.

Код: Выделить всё
unit cloud;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, FileUtil, Buttons, ExtCtrls, StdCtrls;

type

  { TForm1 }

  TForm1 = class(TForm)
    Button1: TButton;
    PaintBox1: TPaintBox;
    Timer1: TTimer;
    procedure FormCreate(Sender: TObject);
  private
   { private declarations }
    //Координаты прорисовки объекта.Доступны всем процедурам класса TForm1
    x1,y1:Integer;
  public
    { public declarations }
    //Процедура прорисовки облака
    procedure Cloud(x,y:Integer; ColorCloud:TColor);
  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}

procedure TForm1.FormCreate(Sender: TObject);
begin

end;

{ TForm1 }
procedure TForm1.Cloud(x,y:Integer; ColorCloud:TColor);
begin
   //Прорисовка облака из двух эллипсов
   with PaintBox1.Canvas do begin
     Pen.Style:=psClear;
     Brush.Color:=ColorCloud;
     Ellipse(x,y,x+80,y+40);
     Ellipse(x+30,y+10,x+100,y+50);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
   //установка начальных значений
   x1:=0;
   y1:=50;
   Timer.Interval:=100;
   //прорисовка картинки по которой двигается объект
   PaintBox1.Canvas.Brush.Color:=clBlue;
   PaintBox1.Canvas.Rectangle(0,0,PaintBox1.Width,PaintBox1.Height);
   //Включение таймера-запуск анимации
   Timer1.Enabled:=true;
   end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
  //закраска объекта цветом фона
  Cloud(x1,y1,clBlue)
  //изменение координат прорисовки
  x1:=x1+1;
  //прорисовка объекта в новом месте
  Cloud(x1,y1,clWhite);
  end;
end.

Очень надеюсь на вашу помощь)

Mire
незнакомец
 
Сообщения: 1
Зарегистрирован: 03.05.2019 10:49:20

Re: Ошибка Fatal: Syntax error, «;» expected

Сообщение Awkward » 04.05.2019 12:14:19

Код: Выделить всё
procedure TForm1.Cloud(x,y:Integer; ColorCloud:TColor);
begin
   //Прорисовка облака из двух эллипсов
   with PaintBox1.Canvas do begin // <<<<< не парный begin
     Pen.Style:=psClear;
     Brush.Color:=ColorCloud;
     Ellipse(x,y,x+80,y+40);
     Ellipse(x+30,y+10,x+100,y+50);
  end; // <<<<<<  вставить
end;
Awkward
новенький
 
Сообщения: 43
Зарегистрирован: 19.01.2017 00:06:47

Re: Ошибка Fatal: Syntax error, «;» expected

Сообщение iskander » 04.05.2019 12:29:38

И еще вот здесь:

Код: Выделить всё
procedure TForm1.Button1Click(Sender: TObject);
begin
   //установка начальных значений
   x1:=0;
   y1:=50;
   Timer.Interval:=100;
   //прорисовка картинки по которой двигается объект
   PaintBox1.Canvas.Brush.Color:=clBlue;
   PaintBox1.Canvas.Rectangle(0,0,PaintBox1.Width,PaintBox1.Height);
   //Включение таймера-запуск анимации
   Timer1.Enabled:=true;
   //end; <-------- убрать лишний end
end;
iskander
энтузиаст
 
Сообщения: 538
Зарегистрирован: 08.01.2012 18:43:34

Re: Ошибка Fatal: Syntax error, «;» expected

Сообщение VirtUX » 05.05.2019 11:27:40

Mire писал(а):procedure TForm1.Timer1Timer(Sender: TObject);
begin
//закраска объекта цветом фона
Cloud(x1,y1,clBlue); <—- тут пропустили «;»
//изменение координат прорисовки
x1:=x1+1;
//прорисовка объекта в новом месте
Cloud(x1,y1,clWhite);
end;

Аватара пользователя
VirtUX
энтузиаст
 
Сообщения: 878
Зарегистрирован: 05.02.2008 10:52:19
Откуда: Крым, Алушта


Вернуться в Lazarus

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

Сейчас этот форум просматривают: Google [Bot] и гости: 7

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    В этом разделе можно создавать темы, которые относятся к поколению 32-битных компиляторов.
    Здесь решаются вопросы портирования кода из старого доброго Турбо Паскаля в FPC, TMT, VP, GPC компиляторы, а также особенностей программирования на них для Windows/Linux и других ОС.
    Указывайте тип компилятора, его версию, а также платформу (Windows/Linux/..) компиляции, другими словами, Target.


    • Библиотека MSDN MSDN Library Online | RSDN — RUSSIAN SOFTWARE DEVELOPER NETWORK
    • Free Pascal manuals [по-русски] | TMT Pascal Reference | VP Manuals

    >
    Ошибки при компилировании в Lazarus при Win32
    , Извините, что создаю тему, просто я искал в других темах и не нашел.. дело вот в чем..

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему



    Сообщ.
    #1

    ,
    11.03.11, 13:09

      я только что начал
      изучать Free Pascal и Lazarus. И по учебнику делаю задание и мне выводит ошибку при компиляции в первой строке.

      ExpandedWrap disabled

        procedure TForm1 . But ton1Click ( Sender : TObject ) ;

        var

        pud , funt : integer ;

        kg : real ;

        begin

        pud:=St rToInt ( Edi t1 . Text ) ;

        funt :=St rToInt ( Edi t2 . Text ) ;

        kg:=pud*16.38+ funt*16.38/40 ;

        Label4 . Caption:= ’В_килограммах:_’+FloatToSt r ( kg ) ;

      все по учебнику перепроверил. все символ в символ, а компилировать не хочет, пишет ошибки

      ExpandedWrap disabled

        unit1.pas(38,2) Error: Illegal expression

        unit1.pas(38,12) Fatal: Syntax error, «;» expected but «identifier TFORM1» found

      помогите пожалуйста. незнаю как быть. :wall:

      Сообщение отредактировано: volvo877 — 11.03.11, 13:18

      Guru

      volvo877



      Сообщ.
      #2

      ,
      11.03.11, 13:20

        Moderator

        *******

        Рейтинг (т): 878

        Ошибка — в коде выше, где-то либо не тот раздел указан, либо не хватает чего-то… Покажи весь код…

        И потом… У тебя вот эти пробелы среди слов что, прямо в коде тоже присутствуют? Их не должно быть. Или ты перепечатываешь сюда? Не надо этого делать. Копируй. Так больше вероятности, что не внесешь еще и во время задавания вопроса ошибку…


        MatriXX



        Сообщ.
        #3

        ,
        11.03.11, 13:27

          ExpandedWrap disabled

            unit Unit1;

            {$mode objfpc}{$H+}

            interface

            uses

              Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,

              StdCtrls;

            type

              { TForm1 }

              TForm1 = class(TForm)

                Button1: TButton;

                Edit1: TEdit;

                Edit2: TEdit;

                Label1: TLabel;

                Label2: TLabel;

                Label3: TLabel;

                Label4: TLabel;

                procedure Button1Click(Sender: TObject);

              private

                { private declarations }

              public

                { public declarations }

              end;

            var

              Form1: TForm1;

            implementation

            { TForm1 }

            begin

             procedure TForm1.But ton1Click(Sender:TObject);

            var

            pud,funt:integer;

            kg:real;

            begin

            pud:=StrToInt(Edit1.Text );

            funt:=StrToInt(Edit2.Text);

            kg:=pud*16.38+funt*16.38/40;

            Label4.Caption:=’В_килограммах:_’+FloatToStr(kg);

            end;

            initialization

              {$I unit1.lrs}

            end.

          вот весь полностью код

          Добавлено 11.03.11, 13:30
          ах даа… пробелы после компиляции(после ее попытки)появились. и если возможно, то покажите наглядно, где и что неправильно. просто я в терминах пока что тупой.. пару дней, как учу всего лишь..

          Сообщение отредактировано: volvo877 — 11.03.11, 13:47

          Guru

          volvo877



          Сообщ.
          #4

          ,
          11.03.11, 13:53

            Moderator

            *******

            Рейтинг (т): 878

            begin в строке №37 — лишний. Убери его, и все заведется… Апострофы тоже замени на прямые ( ‘вот такие’ ). Пользуйся подсветкой, ее не просто для красоты продумали, ведь ясно видно, что твоя «В_килограммах:_» за строку не считается… Считается — когда подсвечена, как строка:

            ExpandedWrap disabled

              unit Unit1;

              {$mode objfpc}{$H+}

              interface

              uses

                Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,

                StdCtrls;

              type

                { TForm1 }

                TForm1 = class(TForm)

                  Button1: TButton;

                  Edit1: TEdit;

                  Edit2: TEdit;

                  Label1: TLabel;

                  Label2: TLabel;

                  Label3: TLabel;

                  Label4: TLabel;

                  procedure Button1Click(Sender: TObject);

                private

                  { private declarations }

                public

                  { public declarations }

                end;

              var

                Form1: TForm1;

              implementation

              { TForm1 }

              procedure TForm1.Button1Click(Sender:TObject);

              var

                pud,funt:integer;

                kg:real;

              begin

                pud:=StrToInt(Edit1.Text );

                funt:=StrToInt(Edit2.Text);

                kg:=pud*16.38+funt*16.38/40;

                Label4.Caption:=’В_килограммах:_’+FloatToStr(kg);

              end;

              initialization

                {$I unit1.lrs}

              end.

            Видишь разницу в цвете?


            MatriXX



            Сообщ.
            #5

            ,
            11.03.11, 14:17

              да!! огромное спасибо!! все получилось)) подозревал ведь, что begin не к месту, но удалять не решался.. и с апострофами спасибо!! :rose: :D

              Добавлено 11.03.11, 14:21
              извиняюсь за отдельные сообщения :oops: просто к аське привык.. и кнопки типа «дополнить» не найду.. еще раз простите.

              P.s. не удаляйте пожалста тему. я буду по мере наобходимости помощи обращаться к Вам. спасибо))

              0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

              0 пользователей:

              • Предыдущая тема
              • 32-битные компиляторы
              • Следующая тема

              Рейтинг@Mail.ru

              [ Script execution time: 0,0669 ]   [ 16 queries used ]   [ Generated: 12.02.23, 18:39 GMT ]  

              Содержание

              1. Fatal: Syntax error, «.» expected but «;» found
              2. 1 Answer 1
              3. Pascal fatal error «;» expected but else founded
              4. 2 Answers 2
              5. Pascal fatal error «;» expected but else founded
              6. 2 Answers 2
              7. [Паскалъ] Need Help
              8. Почему выдаёт ошибку? Где я накосячила? Ошибка: unit1.pas(120,5) Fatal: Syntax error, «;» expected but «ELSE» found

              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 fatal error «;» expected but else founded

              What is causing the fatal error «;» expected but else founded message?

              2 Answers 2

              Unlike C, in Pascal a semicolon ; separates statements, it does not terminate them, and the then clause requires a single statement. then WriteLn(. ); else is two statements; you want then WriteLn(. ) else .

              Let’s take this opportunity to learn how to read and use error messages to your advantage.

              The compiler tells you exactly what the error is (it’s a ; before an else , because both of those are mentioned in the error message). It also gives you the exact line number where it’s reporting the error; that’s the number (usually in parentheses right before the error message, like (from Delphi):

              [DCC Error] Project2.dpr(14): E2153 ‘;’ not allowed before ‘ELSE’

              So the error is happening on line 14 (in my code — your number will be different). Let’s look at that line and a few before and after:

              So look at the error message:

              That clearly tells you that the ; in the line before the else is the problem (that’s very clear, because it says not allowed), so remove it.

              BTW, now you’re going to get another error:

              [DCC Error] Project2.dpr(15): E2003 Undeclared identifier: ‘wrtieln’

              I think you should be able to figure that one out; again, the compiler gives you the exact line number.

              You’re going to get another one, if you’ve posted your entire code:

              [DCC Error] Project2.dpr(18): E2029 Statement expected but end of file found

              This is because you’ve left out the end. that marks the end of a program file in Pascal. If you’ve not posted your entire code, you may not get it.

              It’s important to learn to actually read the words when you get an error message from the compiler. In most languages, the messages are clearly worded, and they all have information you can use to try to figure out (or at least narrow down) the problems in your code.

              Источник

              Pascal fatal error «;» expected but else founded

              What is causing the fatal error «;» expected but else founded message?

              2 Answers 2

              Unlike C, in Pascal a semicolon ; separates statements, it does not terminate them, and the then clause requires a single statement. then WriteLn(. ); else is two statements; you want then WriteLn(. ) else .

              Let’s take this opportunity to learn how to read and use error messages to your advantage.

              The compiler tells you exactly what the error is (it’s a ; before an else , because both of those are mentioned in the error message). It also gives you the exact line number where it’s reporting the error; that’s the number (usually in parentheses right before the error message, like (from Delphi):

              [DCC Error] Project2.dpr(14): E2153 ‘;’ not allowed before ‘ELSE’

              So the error is happening on line 14 (in my code — your number will be different). Let’s look at that line and a few before and after:

              So look at the error message:

              That clearly tells you that the ; in the line before the else is the problem (that’s very clear, because it says not allowed), so remove it.

              BTW, now you’re going to get another error:

              [DCC Error] Project2.dpr(15): E2003 Undeclared identifier: ‘wrtieln’

              I think you should be able to figure that one out; again, the compiler gives you the exact line number.

              You’re going to get another one, if you’ve posted your entire code:

              [DCC Error] Project2.dpr(18): E2029 Statement expected but end of file found

              This is because you’ve left out the end. that marks the end of a program file in Pascal. If you’ve not posted your entire code, you may not get it.

              It’s important to learn to actually read the words when you get an error message from the compiler. In most languages, the messages are clearly worded, and they all have information you can use to try to figure out (or at least narrow down) the problems in your code.

              Источник

              [Паскалъ] 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

              Источник

              Почему выдаёт ошибку? Где я накосячила? Ошибка: 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 identifier writeln found
            • Fatal syntax error expected but identifier write found
            • Fatal syntax error expected but const char found
            • Fatal syntax error begin expected but end of file found lazarus
            • Fatal string manager failed to initialize properly как исправить ошибку

            • 0 0 голоса
              Рейтинг статьи
              Подписаться
              Уведомить о
              guest

              0 комментариев
              Старые
              Новые Популярные
              Межтекстовые Отзывы
              Посмотреть все комментарии