一个计算四则表达式的模板

一个计算四则表达式的模板,第1张

一个计算四则表达式的模板,第2张

给大家分享一个非常方便的函数模板,可以且只能计算四个带括号的表达式。只有一个函数接口:int getexpvalue (_ tstream & istrin,_ t & nreturn)
参数解释:
istrin:输入流,可以是标准IO流或文件流,或者stream
nReturn:用于接收计算结果的变量,计算中使用的类型由该变量决定。
返回值:非零值表示计算成功,零值表示计算失败并出现错误。

程序代码:

命名空间fy _ Exp {
命名空间{ template
inline _ T get Exp value(_ T T[],char & csym){
char c = csym;csym = 0;
开关(c){
case '+':return t[0]+= t[1];
case '-':返回t[0]-= t[1];
case ' * ':return t[0]* = t[1];
默认值:return t[0]/= t[1];//case '/':
}
} }
template
/* _Tstream:inputstream,_ T:获取返回值
*成功获取值则返回非零值*/
int get exp value(_ Tstream & istrin,_ T & n Return){
_ T[3]= { 0 };//雨燕
char csym[3]= " ++ ";
int nLevel = 1,nERR = 0;
如果(!(istrin > > t[1]))istrin . clear();
for(;;){
if(istrin > > csym[2]){
switch(csym[2]){
case '(':
if(!csym[1]){ n level = 0x 100;nERR = 1;}else
if(!GetExpValue(istrin,t[2]))n level | = 0x 10;
else { n level = 0x 100;nERR = 1;}
break;
case ')':
{ n level = 0x 100;}破;
case '+':case '-':case ' * ':case '/':
{ csym[nLevel ++]= csym[2];}破;
case“”:case“\ r”:case“\ n”:case“\ t”:continue;
默认值:
{ n level = 0x 100;nERR = 1;}
}
if(n level = = 0x 100)break;
if(n level & 0x 10 | | istrin > > t[2]){
n level & = 0xF;
if(n level = = 1){ t[1]= t[2];csym[1]= 0;继续;}
if(csym[1]= = ' * ' | | csym[1]= = '/'){
get exp value(t+1,csym[1]);
}
else {
GetExpValue(t,csym[0]);
t[1]= t[2];csym[0]= csym[1];csym[1]= 0;
}
n level = 1;
}
else istrin . clear();
}
else { nERR =-1;打破;}
}
if(csym[1])t[2]= 0,nReturn=GetExpValue(t+1,csym[1]);
else n return = get exp value(t,csym[0]);
return nERR==-1?1:0;
}}


使用函数模板的示例:
在上面的代码后添加下面的代码:

程序代码:

#include
#include
#include
using namespace std;
int main(void)
{
string s1;
while(cin >>s1)
{
istrstream isin(s1.data());
double d;
if(fy_Exp::GetExpValue(isin, d))
{
cout

DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
白度搜_经验知识百科全书 » 一个计算四则表达式的模板

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情