几个函数

来源:互联网 发布:淘宝值得买的小东西 编辑:程序博客网 时间:2024/04/28 14:32
1.转换函数
string convertIntToString(int n)//int转换成string
{
 stringstream sstr;
 
string str;
 sstr
<<n;
 sstr
>>str;
 
return str;
}

string convertDoubleToString(double n)//double转换成string
{
 stringstream sstr;
 
string str;
 sstr
<<n;
 sstr
>>str;
 
return str;
}


double convertStringToDouble(string str)
{
 
double result=0;
 
int len=str.length();
 
for(int i=0;i<len-1;i++)
 
{
  
if(str[i]=='.')
  
{
   result
=0;
   
double index=1;
   
for(int j=i-1;j>=0;j--)
   
{
    
int tmp=str[j]-'0';
    result
+=tmp*index;
    index
*=10;
   }

   index
=0.1;
   
for(int k=i+1;k<=len-1;k++)
   
{
    
int tmp=str[k]-'0';
    result
+=tmp*index;
    index
*=0.1;
   }

   
return result;
  }

 }

 
int index=1;
 
for(int l=len-1;l>=0;l--)
 
{
  
double tmp=str[l]-'0';
  result
+=tmp*index;
  
  index
*=10;
 }

 
return result;
}

//string 转换成int
int convertStringToInt(string str)
{
 
  
int len=str.length();
 
int index=1;
 
int result=0;
 
for(int l=len-1;l>=0;l--)
 
{
  
int tmp=str[l]-'0';
  result
+=tmp*index;
  
  index
*=10;
 }

 
return result;
}

 

2. 表达式求值

 

const int ESIZE=60;
double s1[ESIZE+1];//操作数
char s2[ESIZE+1];//运算符
int t1,t2;
//一次运算
void calcu()
{
 
double x1,x2,x;
 
char p;
 
//弹出一个运算符
 p=s2[t2--];
 
//弹出两个操作数
 x2=s1[t1--];
 x1
=s1[t1--];
 
//计算
 switch(p)
 
{
 
case '+':
  x
=x1+x2;
  
break;
 
case '-':
  x
=x1-x2;
  
break;
 
case '*':
  x
=x1*x2;
  
break;
 
case '/':
  x
=x1/x2;
  
break;
 }

 
//结果入栈
 s1[++t1]=x;
}

double calculator(vector<string> vec)
{
 
//去掉两端的括号
 while((vec.at(0)=="(")&&(vec.at(vec.size()-1)==")"))
 
{
  vec.pop_back();
  vector
<string>::iterator tit=vec.begin();
  vec.erase(tit);
 }

 
char c;
 
double v;
 vector
<string>::iterator it=vec.begin();
 
//设置空栈
 t1=t2=0;
 
 
//第一个字符
 c=(*it)[0];
 
while(it!=vec.end())
 
{
  
switch(c)
  
{
  
case '+':
  
case'-':
   
if(t2&&(s2[t2]!='('))
   
{
    
//执行选遇到的加减乘除运算
    calcu();
   }

   
//当前运算符进栈
   s2[++t2]=c;
   
//读下一个
   it++;
   c
=(*it)[0];
   
break;
  
case '*':
  
case '/':
   
if(t2&&(s2[t2]=='*'||s2[t2]=='/'))
   
{
    
//执行先遇到的乘,除运算
    calcu();
   }

   
//当前运算符进栈
   s2[++t2]=c;
   
//读下一个
   it++;
   c
=(*it)[0];
   
break;
  
case '(':
   
//左括号进栈
   s2[++t2]=c;
   
//读下一个
   it++;
   c
=(*it)[0];
   
break;
  
case ')':
   
if(s2[t2]!='(')
   
{
    
//执行括号内加减乘除运算
    calcu();
   }

   
//弹出左括号
   t2--;
   
//读下一个
   it++;
   
if(it!=vec.end())
   c
=(*it)[0];
   
break;
  
default:
   
//数字转成double
   v=convertStringToDouble(*it);
   
//操作数进栈
   s1[++t1]=v;
   
//读下一个
   it++;
   
if(it!=vec.end())
   
{
    c
=(*it)[0];
   }

   
break;
  }

 }

 
while(t2)
  calcu();
 
return s1[t1];

}

 

 

原创粉丝点击