IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Delphi Discussion :

Évaluer une expression arithmétique


Sujet :

Delphi

  1. #1
    Futur Membre du Club
    Inscrit en
    Décembre 2009
    Messages
    10
    Détails du profil
    Informations forums :
    Inscription : Décembre 2009
    Messages : 10
    Points : 9
    Points
    9
    Par défaut Évaluer une expression arithmétique
    Bonjour,
    Je cherche un outil pour évaluer une expression arithmétique du genre ((1+2) * 4) + 3
    Merci

  2. #2
    Rédacteur/Modérateur

    Avatar de SergioMaster
    Homme Profil pro
    Développeur informatique retraité
    Inscrit en
    Janvier 2007
    Messages
    15 043
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 67
    Localisation : France, Loire Atlantique (Pays de la Loire)

    Informations professionnelles :
    Activité : Développeur informatique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Janvier 2007
    Messages : 15 043
    Points : 40 957
    Points
    40 957
    Billets dans le blog
    62
    Par défaut
    Bonjour, quelle version de Delphi ?
    Si vous avez une version > XE2 le moteur livebindings peut le faire voir cet article
    pour des expressions plus complexe et avant les LiveBindings , j'ai utilisé des bibliothèques plus copieuses mais il faudrait que je retrouve les liens, cela fait bien 15 ans

    [Edit] voilà ce que j'utilisais à l'époque D3 comme "parser", fortement inspiré d'une unité trouvée sur le net mais je ne retrouve pas les informations d'origine
    (désolé pour l'auteur mais en général je regroupe toutes les informations ailleurs)
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
     
    unit Parser;
     
    interface
     
    uses Dialogs, SysUtils;
     
    const
      EXPLIMIT = 11356;
      SQRLIMIT = 1E2466;
      MAXPLACES = 8;
      MAXEXPLEN = 4;
      PARSERSTACKSIZE = 20;
      MSGSTACKERROR = 'Dépassement de la capacité d''évaluation de la Formule.';
      LETTERS : set of Char = ['A'..'Z', 'a'..'z'];
      VARIABLE : set of Char =['0'..'9','A'..'Z', 'a'..'z'];
     
    function Parse(S : String;CellValue : Real ;var Att : Word) : Real;
    { Parses the string s - returns the Value of the evaluated string, and puts
       the attribute in Att: FORMULA = 2, ERROR=0.
    }
     
    implementation
     
    const
      PLUS = 0;
      MINUS = 1;
      TIMES = 2;
      DIVIDE = 3;
      EXPO = 4;
      COLON = 5;
      OPAREN = 6;
      CPAREN = 7;
      NUM = 8;
      CELLT = 9;
      FUNC = 10;
      EOL = 11;
      BAD = 12;
      MAXFUNCNAMELEN = 5;
      TXT = 0;
      VALUE = 1;
      FORMULA = 2;
     
     
      type
      TokenRec = record
        State : Byte;
        case Byte of
          0 : (Value : Real);
          1 : (Row, Col : Word);
          2 : (FuncName : String[MAXFUNCNAMELEN]);
      end;
     
      var
      Stack : array [1..PARSERSTACKSIZE] of TokenRec;
      CurToken : TokenRec;
      StackTop, TokenType : Word;
      MathError, TokenError, IsFormula : Boolean;
      Input : String;
     
    function IsFunc(S : String) : Boolean;
    { Checks to see if the start of the Input string is a legal function.
      Returns TRUE if it is, FALSE otherwise.
    }
    var
      Len : Word;
    begin
      Len := Length(S);
      if Pos(S, Input) = 1 then
      begin
        CurToken.FuncName := Copy(Input, 1, Len);
        Delete(Input, 1, Len);
        IsFunc := True;
      end
      else
        IsFunc := False;
    end; { IsFunc }
     
    function VariableStart (Input : String; Place : Word; var FormLen : Word) : Boolean;
    var
      OldPlace : Word;
    begin
      VariableStart := False;
      OldPlace := Place;
      if not (Input[Place] in VARIABLE) then
        Exit;
      Inc(Place);
      while Input[Place] in VARIABLE do Inc(Place);
      FormLen := Place - OldPlace;
      VariableStart := True;
    end; { FormulaStart }
     
     
    function NextToken : Word;
    { Gets the next Token from the Input stream }
    var
      NumString : String[80];
      FormLen, Len, NumLen : Word;
      Check : Integer;
      Decimal : Boolean;
    begin
      if Input = '' then
      begin
        NextToken := EOL;
        Exit;
      end;
      while (Input <> '') and (Input[1] = ' ') do
        Delete(Input, 1, 1);
      if Input[1] in ['0'..'9', '.'] then
      begin
        NumString := '';
        Len := 1;
        Decimal := False;
        while (Len <= Length(Input)) and
              ((Input[Len] in ['0'..'9']) or
               ((Input[Len] = '.') and (not Decimal))) do
        begin
          NumString := NumString + Input[Len];
          if Input[1] = '.' then
            Decimal := True;
          Inc(Len);
        end;
        if (Len = 2) and (Input[1] = '.') then
        begin
          NextToken := BAD;
          Exit;
        end;
        if (Len <= Length(Input)) and (Input[Len] = 'E') then
        begin
          NumString := NumString + 'E';
          Inc(Len);
          if Input[Len] in ['+', '-'] then
          begin
            NumString := NumString + Input[Len];
            Inc(Len);
          end;
          NumLen := 1;
          while (Len <= Length(Input)) and (Input[Len] in ['0'..'9']) and
                (NumLen <= MAXEXPLEN) do
          begin
            NumString := NumString + Input[Len];
            Inc(NumLen);
            Inc(Len);
          end;
        end;
        if NumString[1] = '.' then
          NumString := '0' + NumString;
        Val(NumString, CurToken.Value, Check);
        if Check <> 0 then
          MathError := True;
        NextToken := NUM;
        Delete(Input, 1, Length(NumString));
        Exit;
      end
      else if Input[1] in LETTERS then
      begin
        if IsFunc('ABS') or
           IsFunc('ATAN') or
           IsFunc('COS') or
           IsFunc('EXP') or
           IsFunc('LN') or
           IsFunc('ROUND') or
           IsFunc('SIN') or
           IsFunc('SQRT') or
           IsFunc('SQR') or
           IsFunc('TRUNC') then
        begin
          NextToken := FUNC;
          Exit;
        end;
        if VariableStart(Input, 1, FormLen) then
        begin
          Delete(Input, 1, FormLen);
          IsFormula := True;
          NextToken := CELLT;
          Exit;
        end
        else begin
          NextToken := BAD;
          Exit;
        end;
      end
      else begin
        case Input[1] of
          '+' : NextToken := PLUS;
          '-' : NextToken := MINUS;
          '*' : NextToken := TIMES;
          '/' : NextToken := DIVIDE;
          '^' : NextToken := EXPO;
          ':' : NextToken := COLON;
          '(' : NextToken := OPAREN;
          ')' : NextToken := CPAREN;
          else
            NextToken := BAD;
        end;
        Delete(Input, 1, 1);
        Exit;
      end; { case }
    end; { NextToken }
     
    procedure Push(Token : TokenRec);
    { Pushes a new Token onto the stack }
    begin
      if StackTop = PARSERSTACKSIZE then
      begin
        MessageDlg(MSGSTACKERROR,mtError,[mbOk],0);
        TokenError := True;
      end
      else begin
        Inc(StackTop);
        Stack[StackTop] := Token;
      end;
    end; { Push }
     
    procedure Pop(var Token : TokenRec);
    { Pops the top Token off of the stack }
    begin
      Token := Stack[StackTop];
      Dec(StackTop);
    end; { Pop }
     
    function GotoState(Production : Word) : Word;
    { Finds the new state based on the just-completed production and the
       top state.
    }
    var
      State : Word;
    begin
      GotoState:=1;
      State := Stack[StackTop].State;
      if (Production <= 3) then
      begin
        case State of
          0 : GotoState := 1;
          9 : GotoState := 19;
          20 : GotoState := 28;
        end; { case }
      end
      else if Production <= 6 then
      begin
        case State of
          0, 9, 20 : GotoState := 2;
          12 : GotoState := 21;
          13 : GotoState := 22;
        end; { case }
      end
      else if Production <= 8 then
      begin
        case State of
          0, 9, 12, 13, 20 : GotoState := 3;
          14 : GotoState := 23;
          15 : GotoState := 24;
          16 : GotoState := 25;
        end; { case }
      end
      else if Production <= 10 then
      begin
        case State of
          0, 9, 12..16, 20 : GotoState := 4;
        end; { case }
      end
      else if Production <= 12 then
      begin
        case State of
          0, 9, 12..16, 20 : GotoState := 6;
          5 : GotoState := 17;
        end; { case }
      end
      else begin
        case State of
          0, 5, 9, 12..16, 20 : GotoState := 8;
        end; { case }
      end;
    end; { GotoState }
     
    procedure Shift(State : Word);
    { Shifts a Token onto the stack }
    begin
      CurToken.State := State;
      Push(CurToken);
      TokenType := NextToken;
    end; { Shift }
     
    procedure Reduce(Reduction : Word;CellValue : Real);
    { Completes a reduction }
    var
      Token1, Token2 : TokenRec;
      Counter : Word;
    begin
      case Reduction of
        1 : begin
          Pop(Token1);
          Pop(Token2);
          Pop(Token2);
          CurToken.Value := Token1.Value + Token2.Value;
        end;
        2 : begin
          Pop(Token1);
          Pop(Token2);
          Pop(Token2);
          CurToken.Value := Token2.Value - Token1.Value;
        end;
        4 : begin
          Pop(Token1);
          Pop(Token2);
          Pop(Token2);
          CurToken.Value := Token1.Value * Token2.Value;
        end;
        5 : begin
          Pop(Token1);
          Pop(Token2);
          Pop(Token2);
          if Token1.Value = 0 then
            MathError := True
          else
            CurToken.Value := Token2.Value / Token1.Value;
        end;
        7 : begin
          Pop(Token1);
          Pop(Token2);
          Pop(Token2);
          if Token2.Value <= 0 then
            MathError := True
          else if (Token1.Value * Ln(Token2.Value) < -EXPLIMIT) or
                  (Token1.Value * Ln(Token2.Value) > EXPLIMIT) then
            MathError := True
          else
            CurToken.Value := Exp(Token1.Value * Ln(Token2.Value));
        end;
        9 : begin
          Pop(Token1);
          Pop(Token2);
          CurToken.Value := -Token1.Value;
        end;
        11 : begin
          Pop(Token1);
          Pop(Token2);
          Pop(Token2);
          CurToken.Value := 0;
          if Token1.Row = Token2.Row then
          begin
            if Token1.Col < Token2.Col then
              TokenError := True
            else begin
              for Counter := Token2.Col to Token1.Col do
                CurToken.Value := CurToken.Value + CellValue;
            end;
          end
          else if Token1.Col = Token2.Col then
          begin
            if Token1.Row < Token2.Row then
              TokenError := True
            else begin
              for Counter := Token2.Row to Token1.Row do
                CurToken.Value := CurToken.Value + CellValue;
            end;
          end
          else
            TokenError := True;
        end;
        13 : begin
          Pop(CurToken);
          CurToken.Value := CellValue;
        end;
        14 : begin
          Pop(Token1);
          Pop(CurToken);
          Pop(Token1);
        end;
        16 : begin
          Pop(Token1);
          Pop(CurToken);
          Pop(Token1);
          Pop(Token1);
          if Token1.FuncName = 'ABS' then
            CurToken.Value := Abs(CurToken.Value)
          else if Token1.FuncName = 'ATAN' then
            CurToken.Value := ArcTan(CurToken.Value)
          else if Token1.FuncName = 'COS' then
            CurToken.Value := Cos(CurToken.Value)
          else if Token1.FuncName = 'EXP' then
          begin
            if (CurToken.Value < -EXPLIMIT) or (CurToken.Value > EXPLIMIT) then
              MathError := True
            else
              CurToken.Value := Exp(CurToken.Value);
          end
          else if Token1.FuncName = 'LN' then
          begin
            if CurToken.Value <= 0 then
              MathError := True
            else
              CurToken.Value := Ln(CurToken.Value);
          end
          else if Token1.FuncName = 'ROUND' then
          begin
            if (CurToken.Value < -1E9) or (CurToken.Value > 1E9) then
              MathError := True
            else
              CurToken.Value := Round(CurToken.Value);
          end
          else if Token1.FuncName = 'SIN' then
            CurToken.Value := Sin(CurToken.Value)
          else if Token1.FuncName = 'SQRT' then
          begin
            if CurToken.Value < 0 then
              MathError := True
            else
              CurToken.Value := Sqrt(CurToken.Value);
          end
          else if Token1.FuncName = 'SQR' then
          begin
            if (CurToken.Value < -SQRLIMIT) or (CurToken.Value > SQRLIMIT) then
              MathError := True
            else
              CurToken.Value := Sqr(CurToken.Value);
          end
          else if Token1.FuncName = 'TRUNC' then
          begin
            if (CurToken.Value < -1E9) or (CurToken.Value > 1E9) then
              MathError := True
            else
              CurToken.Value := Trunc(CurToken.Value);
          end;
        end;
        3, 6, 8, 10, 12, 15 : Pop(CurToken);
      end; { case }
      CurToken.State := GotoState(Reduction);
      Push(CurToken);
    end; { Reduce }
     
    function Parse;
    var
      FirstToken : TokenRec;
      Accepted : Boolean;
    begin
      Accepted := False;
      TokenError := False;
      MathError := False;
      IsFormula := False;
      Input := UpperCase(S);
      StackTop := 0;
      FirstToken.State := 0;
      FirstToken.Value := 0;
      Push(FirstToken);
      TokenType := NextToken;
      repeat
        case Stack[StackTop].State of
          0, 9, 12..16, 20 : begin
            if TokenType = NUM then
              Shift(10)
            else if TokenType = CELLT then
              Shift(7)
            else if TokenType = FUNC then
              Shift(11)
            else if TokenType = MINUS then
              Shift(5)
            else if TokenType = OPAREN then
              Shift(9)
            else
              TokenError := True;
          end;
          1 : begin
            if TokenType = EOL then
              Accepted := True
            else if TokenType = PLUS then
              Shift(12)
            else if TokenType = MINUS then
              Shift(13)
            else
              TokenError := True;
          end;
          2 : begin
            if TokenType = TIMES then
              Shift(14)
            else if TokenType = DIVIDE then
              Shift(15)
            else
              Reduce(3,CellValue);
          end;
          3 : Reduce(6,CellValue);
          4 : begin
           if TokenType = EXPO then
             Shift(16)
           else
             Reduce(8,CellValue);
          end;
          5 : begin
            if TokenType = NUM then
              Shift(10)
            else if TokenType = CELLT then
              Shift(7)
            else if TokenType = FUNC then
              Shift(11)
            else if TokenType = OPAREN then
              Shift(9)
            else
              TokenError := True;
          end;
          6 : Reduce(10,CellValue);
          7 : begin
            if TokenType = COLON then
              Shift(18)
            else
              Reduce(13,CellValue);
          end;
          8 : Reduce(12,CellValue);
          10 : Reduce(15,CellValue);
          11 : begin
            if TokenType = OPAREN then
              Shift(20)
            else
              TokenError := True;
          end;
          17 : Reduce(9,CellValue);
          18 : begin
            if TokenType = CELLT then
              Shift(26)
            else
              TokenError := True;
          end;
          19 : begin
            if TokenType = PLUS then
              Shift(12)
            else if TokenType = MINUS then
              Shift(13)
            else if TokenType = CPAREN then
              Shift(27)
            else
              TokenError := True;
          end;
          21 : begin
            if TokenType = TIMES then
              Shift(14)
            else if TokenType = DIVIDE then
              Shift(15)
            else
              Reduce(1,CellValue);
          end;
          22 : begin
            if TokenType = TIMES then
              Shift(14)
            else if TokenType = DIVIDE then
              Shift(15)
            else
              Reduce(2,CellValue);
          end;
          23 : Reduce(4,CellValue);
          24 : Reduce(5,CellValue);
          25 : Reduce(7,CellValue);
          26 : Reduce(11,CellValue);
          27 : Reduce(14,CellValue);
          28 : begin
            if TokenType = PLUS then
              Shift(12)
            else if TokenType = MINUS then
              Shift(13)
            else if TokenType = CPAREN then
              Shift(29)
            else
              TokenError := True;
          end;
          29 : Reduce(16,CellValue);
        end; { case }
      until Accepted or TokenError;
      if TokenError then
      begin
        Att := TXT;
        Parse := 0;
        Exit;
      end;
      if IsFormula then
        Att := FORMULA
      else
        Att := VALUE;
      if MathError then
      begin
        Inc(Att, 4);
        Parse := 0;
        Exit;
      end;
      Parse := Stack[StackTop].Value;
    end; { Parse }
     
    end.
    Utilisation :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    procedure TParam_Mat.Test1Click(Sender: TObject);
    var Resultat:Real;
        Att  :Word;
    const MsgString = 'Formule Correcte%s 1 %s = %f %s';
    begin
    with Data_Param.TUnites do
     begin
     Resultat:=Parse(Formule1.text,1,Att);
     if Att=0 then
       MessageDlg('Formule Fausse',mtError,[mbOK],0)
     else
       MessageDlg(Format(MsgString,[#13,FieldByName('UNITE').asString
                 ,Resultat,FieldbyName('UNITE_CONVERSION').AsString]),
                   mtInformation,[mbOk],0);
     end;{with}
    end;
    A noter que JCL contient une classe TEvaluator certainement beaucoup plus efficace
    MVP Embarcadero
    Delphi installés : D3,D7,D2010,XE4,XE7,D10 (Rio, Sidney), D11 (Alexandria), D12 (Athènes)
    SGBD : Firebird 2.5, 3, SQLite
    générateurs États : FastReport, Rave, QuickReport
    OS : Window Vista, Windows 10, Windows 11, Ubuntu, Androïd

  3. #3
    Expert éminent sénior
    Avatar de Paul TOTH
    Homme Profil pro
    Freelance
    Inscrit en
    Novembre 2002
    Messages
    8 964
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Freelance
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2002
    Messages : 8 964
    Points : 28 445
    Points
    28 445
    Par défaut
    pour le fun, voici un programme que j'ai écrit en sous Turbo Pascal en 1994 ! il me permettait de taper des formules en ligne de commande sous DOS

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
     
    Program Calcul;
    { Exemple d'analyse de fonction math‚matique (+ - * /) }
    Var
     Exp:string;
     Ex:byte;
     Analyse:string;
     
    Procedure CopierNombre;
     begin
      While Exp[Ex] in ['0'..'9'] do begin
       Analyse:=Analyse+Exp[Ex]; Inc(Ex);
      end;
      if Exp[Ex] in ['.',','] then begin
       Analyse:=Analyse+'.'; Inc(Ex);
       While Exp[Ex] in ['0'..'9'] do begin
        Analyse:=Analyse+Exp[Ex]; Inc(Ex);
       end;
      end;
      Analyse:=Analyse+'|';
     end;
     
    Procedure Espace; begin While Exp[Ex]=' ' do inc(Ex); end;
     
    Procedure Erreur;
     begin
      Writeln('Erreur dans la formule'); Writeln(Exp);
      While Ex>1 do begin write(' '); dec(Ex); end; WriteLn('^');
      Halt;
     end;
     
    Procedure Expression; forward;
     
    Procedure Signe;
     var
      positif:boolean;
     begin
      Espace;
      positif:=True;
      While Exp[Ex] in ['+','-',' '] do begin
       if Exp[Ex]='-' then positif:=not positif; Inc(Ex);
      end;
      if not positif then Analyse:=Analyse+'\';
      Espace;
     end;
     
    Procedure Facteur; { nombre|Expression }
     begin
      Signe;
      case Exp[Ex] of
       '0'..'9':CopierNombre;
       '(':begin
            Inc(Ex); Expression;
            If Exp[Ex]=')' then Inc(Ex)
             else begin Writeln('Attendu ")"'); Erreur; end;
           end;
       Else Erreur;
      end;
      Espace;
     end;
     
    Procedure Terme; { Facteur [(*|/) Facteur] }
     var op:char;
     begin
      Facteur;
      While Exp[Ex] in ['/','*'] do begin
       op:=Exp[Ex]; inc(Ex);
       Facteur; Analyse:=Analyse+op;
      end;
     end;
     
    Procedure Expression; { Terme [(+|-) Terme] }
     Var
      op:char;
     begin
      Terme;
      while Exp[Ex] in ['+','-'] do begin
       op:=Exp[Ex]; inc(Ex);
       Terme; Analyse:=Analyse+op;
      end;
     end;
     
    Const
     TaillePile=1000;
     Px:Word=0;
    Var
     Pile:Array[1..TaillePile] of real;
     
    Procedure Push(v:real);
     begin Inc(Px); Pile[Px]:=v; end;
    Procedure Pop(var v:real);
     begin v:=Pile[Px]; Dec(Px); end;
     
    Procedure Compute;
     var i:byte;
         v:real;
         v1,v2:real;
         decimal:boolean;
         diviseur:real;
         s:string;
     begin
      i:=1; v:=0; decimal:=false; diviseur:=1;
      While i<=Length(Analyse) do begin
       Case Analyse[i] of
        '0'..'9':begin
                  v:=v*10+Ord(Analyse[i])-Ord('0');
                  if decimal then diviseur:=10*diviseur;
                 end;
        ',','.' :begin decimal:=true; end;
        '\'     :begin diviseur:=-diviseur; end;
        '|'     :begin push(v/diviseur); v:=0; diviseur:=1; decimal:=false; end;
        '+'     :begin pop(v2); pop(v1); push(v1 + v2); end;
        '-'     :begin pop(v2); pop(v1); push(v1 - v2); end;
        '/'     :begin
                  pop(v2); pop(v1);
                  if v2=0 then begin Writeln('division par 0'); halt; end;
                  push(v1 / v2);
                 end;
        '*'     :begin pop(v2); pop(v1); push(v1 * v2); end;
       end;
       inc(i);
      end;
      pop(v); Str(v:0:10,s);
      While (Length(s)>1)and(s[Length(s)]='0') do Delete(s,length(s),1);
      Writeln(Exp,'= ',s);
     end;
     
    Procedure Syntaxe;
     begin
      Writeln('Calculatrice v1.0 par TOTH Paul - (C)MySoft 1994.');
      Writeln(' Usage : CALCUL [?] [expression  math‚matique]');
      Writeln(' fonctions disponibles : + - / *');
      Halt(0);
     end;
     
    Var
     i:byte;
     d:byte;
    begin
     If Paramcount=0 then syntaxe;
     if Paramstr(1)='/?' then syntaxe;
     Exp:=''; Ex:=1; Analyse:='';
     if Paramstr(1)='?' then d:=2 else d:=1;
     For i:=d to ParamCount do Exp:=Exp+Paramstr(i)+' ';
     Expression; If Ex<Length(Exp) then Erreur;
     if d=2 then Writeln(Analyse);
     Compute;
    end.
    l'indentation est assez particulière, mais rappelez vous qu'à l'époque on programmait sur des écrans texte en 80x25, il fallait optimiser l'espace
    Developpez.com: Mes articles, forum FlashPascal
    Entreprise: Execute SARL
    Le Store Excute Store

  4. #4
    Futur Membre du Club
    Inscrit en
    Décembre 2009
    Messages
    10
    Détails du profil
    Informations forums :
    Inscription : Décembre 2009
    Messages : 10
    Points : 9
    Points
    9
    Par défaut Expression Parser
    Merci, beaucoup très cher ami, je vais essayer votre solution

    Citation Envoyé par Paul TOTH Voir le message
    pour le fun, voici un programme que j'ai écrit en sous Turbo Pascal en 1994 ! il me permettait de taper des formules en ligne de commande sous DOS

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
     
    Program Calcul;
    { Exemple d'analyse de fonction math‚matique (+ - * /) }
    Var
     Exp:string;
     Ex:byte;
     Analyse:string;
     
    Procedure CopierNombre;
     begin
      While Exp[Ex] in ['0'..'9'] do begin
       Analyse:=Analyse+Exp[Ex]; Inc(Ex);
      end;
      if Exp[Ex] in ['.',','] then begin
       Analyse:=Analyse+'.'; Inc(Ex);
       While Exp[Ex] in ['0'..'9'] do begin
        Analyse:=Analyse+Exp[Ex]; Inc(Ex);
       end;
      end;
      Analyse:=Analyse+'|';
     end;
     
    Procedure Espace; begin While Exp[Ex]=' ' do inc(Ex); end;
     
    Procedure Erreur;
     begin
      Writeln('Erreur dans la formule'); Writeln(Exp);
      While Ex>1 do begin write(' '); dec(Ex); end; WriteLn('^');
      Halt;
     end;
     
    Procedure Expression; forward;
     
    Procedure Signe;
     var
      positif:boolean;
     begin
      Espace;
      positif:=True;
      While Exp[Ex] in ['+','-',' '] do begin
       if Exp[Ex]='-' then positif:=not positif; Inc(Ex);
      end;
      if not positif then Analyse:=Analyse+'\';
      Espace;
     end;
     
    Procedure Facteur; { nombre|Expression }
     begin
      Signe;
      case Exp[Ex] of
       '0'..'9':CopierNombre;
       '(':begin
            Inc(Ex); Expression;
            If Exp[Ex]=')' then Inc(Ex)
             else begin Writeln('Attendu ")"'); Erreur; end;
           end;
       Else Erreur;
      end;
      Espace;
     end;
     
    Procedure Terme; { Facteur [(*|/) Facteur] }
     var op:char;
     begin
      Facteur;
      While Exp[Ex] in ['/','*'] do begin
       op:=Exp[Ex]; inc(Ex);
       Facteur; Analyse:=Analyse+op;
      end;
     end;
     
    Procedure Expression; { Terme [(+|-) Terme] }
     Var
      op:char;
     begin
      Terme;
      while Exp[Ex] in ['+','-'] do begin
       op:=Exp[Ex]; inc(Ex);
       Terme; Analyse:=Analyse+op;
      end;
     end;
     
    Const
     TaillePile=1000;
     Px:Word=0;
    Var
     Pile:Array[1..TaillePile] of real;
     
    Procedure Push(v:real);
     begin Inc(Px); Pile[Px]:=v; end;
    Procedure Pop(var v:real);
     begin v:=Pile[Px]; Dec(Px); end;
     
    Procedure Compute;
     var i:byte;
         v:real;
         v1,v2:real;
         decimal:boolean;
         diviseur:real;
         s:string;
     begin
      i:=1; v:=0; decimal:=false; diviseur:=1;
      While i<=Length(Analyse) do begin
       Case Analyse[i] of
        '0'..'9':begin
                  v:=v*10+Ord(Analyse[i])-Ord('0');
                  if decimal then diviseur:=10*diviseur;
                 end;
        ',','.' :begin decimal:=true; end;
        '\'     :begin diviseur:=-diviseur; end;
        '|'     :begin push(v/diviseur); v:=0; diviseur:=1; decimal:=false; end;
        '+'     :begin pop(v2); pop(v1); push(v1 + v2); end;
        '-'     :begin pop(v2); pop(v1); push(v1 - v2); end;
        '/'     :begin
                  pop(v2); pop(v1);
                  if v2=0 then begin Writeln('division par 0'); halt; end;
                  push(v1 / v2);
                 end;
        '*'     :begin pop(v2); pop(v1); push(v1 * v2); end;
       end;
       inc(i);
      end;
      pop(v); Str(v:0:10,s);
      While (Length(s)>1)and(s[Length(s)]='0') do Delete(s,length(s),1);
      Writeln(Exp,'= ',s);
     end;
     
    Procedure Syntaxe;
     begin
      Writeln('Calculatrice v1.0 par TOTH Paul - (C)MySoft 1994.');
      Writeln(' Usage : CALCUL [?] [expression  math‚matique]');
      Writeln(' fonctions disponibles : + - / *');
      Halt(0);
     end;
     
    Var
     i:byte;
     d:byte;
    begin
     If Paramcount=0 then syntaxe;
     if Paramstr(1)='/?' then syntaxe;
     Exp:=''; Ex:=1; Analyse:='';
     if Paramstr(1)='?' then d:=2 else d:=1;
     For i:=d to ParamCount do Exp:=Exp+Paramstr(i)+' ';
     Expression; If Ex<Length(Exp) then Erreur;
     if d=2 then Writeln(Analyse);
     Compute;
    end.
    l'indentation est assez particulière, mais rappelez vous qu'à l'époque on programmait sur des écrans texte en 80x25, il fallait optimiser l'espace

Discussions similaires

  1. [Turbo Pascal] Evaluation d'une expression arithmétique post-fixée
    Par simousoft dans le forum Turbo Pascal
    Réponses: 3
    Dernier message: 28/01/2012, 20h35
  2. Réponses: 9
    Dernier message: 21/01/2009, 07h54
  3. Réponses: 8
    Dernier message: 15/05/2007, 11h02
  4. [Source] Evaluer une expression algébrique
    Par Delbeke dans le forum Vos contributions VB6
    Réponses: 6
    Dernier message: 22/08/2006, 11h52
  5. Evaluation d'une expression arithmétique
    Par MysticKhal_0 dans le forum Algorithmes et structures de données
    Réponses: 9
    Dernier message: 10/03/2006, 18h25

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo