c++
a=str.find_first_of(op,1); //表示从str字符串的1位置开始查找op字符串;
若找到:a==string::npos;
否则:a!=string::npos;
计算表达式
#include "iostream"
#include "cstdio"
#include "string"
#include "stack"
#include "vector"
#include "stdlib.h"
using namespace std;
int judge(char c1, char c2) { //比较栈顶和输入字符比较级
int a1, a2;
if('+' == c1 || '-' == c1) //栈顶c1,输入c2
a1 = 3;
if('*' == c1 || '/' == c1)
a1 = 5;
if('(' == c1)
a1 = 1;
if(')' == c1)
a1 = 7;
if('#' == c1)
a1 = 0;
if('+' == c2 || '-' == c2)
a2 = 2;
if('*' == c2 || '/' == c2)
a2 = 4;
if('(' == c2)
a2 = 6;
if(')' == c2)
a2 = 1;
if('#'==c2)
a2=0;
if(a1 > a2)
return 1;
if(a1 < a2)
return -1;
if(a1 == a2)
return 0;
}
double run(char c, double d1, double d2) { //四则运算
switch (c) {
case '+':
return d1 + d2;
break;
case '-':
return d1 - d2;
break;
case'*':
return d1 * d2;
break;
case '/':
return d1 / d2;
break;
default:
return 0.0;
break;
}
}
double cal(string str) {
const char * op ="+-*/()#"; //比较的算术符号
str.append(1,'#'); //附加#以便比较
stack<char> optr; //算术符栈
stack<double> optd; //数字栈
int a=-1;
optr.push('#'); //入栈
while(true){
int b=a+1;
a=str.find_first_of(op,a+1); //从a+1处查找运算符
if(a == string::npos) break; //未找到
if(a!=b){
string ss(str,b,a-b); //定义子串
double d=atof(ss.c_str()); //转化
optd.push(d);
}
int ju =judge(optr.top(),str[a]);
if(-1==ju){
optr.push(str[a]);
}
if(0==ju){
optr.pop();
}
if(1==ju){ //出栈计算再将结果入栈
double d1=optd.top();
optd.pop();
double d2=optd.top();
optd.pop();
d1=run(optr.top(),d2,d1);
optd.push(d1);
optr.pop();
a--;
}
}
str.erase(str.length()-1,1); //消除字符
return optd.top();
}
int main() {
int n;
cin >> n;
const int m=n;
vector<double> display(n+1);
while(n>0){
string str;
cin>>str;
double result=cal(str);
display[n]=result;
n--;
};
for(int j=m;j>0;j--){
printf("%.1f\n",display[j]);
}
system("pause");
return 0;
}