JackosKingLe 03/07/2004 à 20:39
Ops gestion du - unaire représenté par un '!'
// az.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
/**********************************************************/
#define EmpilerOp(pExp) Op[iOp++]=(pExp)
#define EmpilerNbr(dNbr) Nbr[iNbr++]=dNbr
#define DepilerNbr() (Nbr[--iNbr])
#define DepilerOp() (Op[--iOp])
/**********************************************************/
int PrioriteOp(char Op)
{
switch(Op)
{
case '+': // binaire ...
case '-':
return 12;
case '*':
case '/':
default:
return 13;
}
}
double calcul(double dNbr1, char Op, double dNbr2)
{
switch(Op)
{
case '+':
return dNbr1+dNbr2;
case '-':
return dNbr1-dNbr2;
case '/':
return dNbr1/dNbr2;
case '*':
default:
return dNbr1*dNbr2;
}
}
double eval(char *pExp)
{
double dNbr,dDec;
char Op1,Op2;
int minus =0;
char Op[500];
double Nbr[500];
int iOp = 0;
int iNbr = 0;
while (*pExp)
if ( *pExp == '+' || *pExp == '-' || *pExp == '/' || *pExp == '*' )
EmpilerOp(*pExp++);
else if ( *pExp == '!')
{
minus++;
pExp++;
}
else
if ( *pExp == '(' )
{
int i=1;
EmpilerNbr(eval(++pExp));
while(i)
{
if (*pExp == ')') i--;
else if (*pExp == '(') i++;
pExp++;
}
}
else if ( *pExp == ')' )
{
for (int i=1;i<iNbr;i++)
Nbr[i] = calcul(Nbr[i-1], Op[i-1],Nbr[i]);
return Nbr[iNbr-1];
}
else
{
dNbr = 0;
while ((*pExp>='0' && *pExp <='9'))
dNbr = dNbr*10 + *pExp++ - '0';
if (*pExp=='.' || *pExp ==',')
{
pExp++;
dDec = 10;
while ((*pExp>='0' && *pExp <='9'))
{
dNbr = dNbr + (*pExp++ - '0')/dDec;
dDec*=10;
}
}
if (minus%2 == 1)
dNbr = -dNbr;
minus = 0;
if (iOp>=2)
{
Op1 = DepilerOp();
Op2 = DepilerOp();
EmpilerOp(Op2);
if ( PrioriteOp(Op1) > PrioriteOp(Op2) ) // on effectue le calcul du haut de la pile
{
dNbr = calcul(DepilerNbr(),Op1,dNbr);
}
else
{
EmpilerOp(Op1);
}
}
EmpilerNbr(dNbr);
}
for (int i=1;i<iNbr;i++)
Nbr[i] = calcul(Nbr[i-1], Op[i-1],Nbr[i]);
return Nbr[iNbr-1];
}
int main(int argc, char* argv[])
{
char Exp[500];
while(true){
cin>>Exp;
if (*Exp == 'q' )
break;
cout<<endl<<"Analyse de l'expression: "<<Exp<<endl;
cout<< "Resultat : "<<eval(Exp)<<endl;
}
return 0;
}
j'attend vos critiques;p