vvhungtam
Tổng số bài gửi : 11 Registration date : 16/09/2007
| Tiêu đề: Tinh Gia Tri Cua Bieu Thuc (Dung Stack) 23/5/2008, 22:05 | |
| - Code:
-
#include <iostream> #include <string> #include <cmath>
using namespace std;
int gt(int x) { int t=1; if(x==0) return 1; for(int i=2;i<=x;i++) t=t*i; return t; } int DoUuTien(char ch) { int i; switch (ch) { case '+': case '-': i=1;break; case '*': case '/': i=2;break; case 'L': case 'N': case 'G': case '^': i=3;break; case '!': case 'S': case 'C': case 'T': i=4;break; default:i=0;break; } return i; } void ChuyenSangHauTo(char* s1,char* s2,int& index) { char stack[100],x,tam[100];strcpy(tam,""); int top=-1;index=-1; strcat(strcat(strcat(tam,"("),s1),")"); strupr(tam); stack[++top]=tam[0]; int k=1; while(top>-1) { x=tam[k]; switch(x) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': s2[++index]=x;break; case '(': stack[++top]=x;break; case '+': case '-': case '*': case '/': case '^': case 'S': case 'C': case 'T': case 'L': case '!': case 'N': case 'G': if(x=='S' && tam[k-1]=='O') break; if(x=='G' && tam[k-1]=='O') break; if(x=='L' && tam[k+1]!='O') break; if(x=='N' && tam[k-1]=='A') break; while(stack[top]!='(') { if(DoUuTien(stack[top])>=DoUuTien(x)) { s2[++index]=' '; s2[++index]=stack[top--]; } else break; } s2[++index]=' '; stack[++top]=x;break; case ')': while(stack[top]!='(') { s2[++index]=' '; s2[++index]=stack[top--]; } top--;break; case ',': s2[++index]=' ';break; } k++; } } float TinhGiaTri(char* s,int index) { float stack[100],t1=0,t2=0,x=0;int top=-1; for(int i=0;i<=index;i++) { if(s[i]>='0' && s[i]<='9') { x=s[i]-48; i++; while(s[i]>='0' && s[i]<='9') { x=x*10+(s[i]-48); ++i; } stack[++top]=x; } else { if(s[i]!=' ') { t1=stack[top--]; t2=stack[top--]; switch(s[i]) { case '+': x=t2+t1;break; case '-': x=t2-t1;break; case '*': x=t2*t1;break; case '/': x=t2/t1;break; case '^': x=pow(t2,t1);break; case 'S': x=sin(t1);stack[++top]=t2;break; case 'C': x=cos(t1);stack[++top]=t2;break; case 'T': x=tan(t1);stack[++top]=t2;break; case 'N': x=log(t1);stack[++top]=t2;break; case 'G': x=log(t1)/log(10);stack[++top]=t2;break; case 'L': x=log(t2)/log(t1);break; case '!': x=gt(t1);stack[++top]=t2;break; } stack[++top]=x; ++i; } } } return stack[top]; } void main() { int dem; char s1[100]; char s2[100]; cout<<"nhap bieu thuc: ";cin>>s1;
ChuyenSangHauTo(s1,s2,dem);//cout<<s2<<endl; cout<<"\nBieu Thuc Co Gia Tri La: \n"; cout<<s1<<" = "<<TinhGiaTri(s2,dem); }
| |
|