我用三個遞迴函數,分別是乘除、加減、括弧
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
using namespace std;
int tdm(string str){//先乘除
int i,r=str.size()-1,c;
for(i=str.size()-1;i>=0;i--){
if(str[i]=='*'||str[i]=='/'||str[i]=='%'){
r=i;
break;
}
}
stringstream stream;
if(r==str.size()-1){
stream<<str;
stream>>c;
return c;
}
stream<<str.substr(r+1);
stream>>c;
switch(str[r]){
case '*':
return tdm(str.substr(0,r))*c;
case '/':
return tdm(str.substr(0,r))/c;
case '%':
return tdm(str.substr(0,r))%c;
}
}
int pm(string str){//再加減
int i,r=str.size()-1,c;
for(i=str.size()-1;i>=0;i--){
if(str[i]=='+'||str[i]=='-'){
r=i;
break;
}
}
if(r==str.size()-1)return tdm(str);
c=tdm(str.substr(r+1));
if(str[r]=='+')return pm(str.substr(0,r))+c;
else return pm(str.substr(0,r))-c;
}
int cal(string str){//判斷括弧(計算)
int i,r1=0,r2=0,c;
for(i=0;i<str.size();i++){
if(str[i]=='(')r1=i;
if(str[i]==')'){
r2=i;
break;
}
}
if(r1==0&&r2==0)return pm(str);
string temp=str.substr(r1+1,r2-r1-1);
c=pm(temp);
string cstr;
stringstream stream;
stream<<c;
stream>>cstr;
return cal(str.substr(0,r1)+cstr+str.substr(r2+1));
}
int main(){
string str;
while(getline(cin,str)){
cout<<cal(str)<<endl;
}
return 0;
}
後來發現要處理負數的問題,所以改了一下:
但仍然卡在line7
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
using namespace std;
int tdm(string str){//time divide mod
int i,r=str.size()-1,c,m=-1;
for(i=str.size()-1;i>=0;i--){
if(str[i]=='-')m=i;
if(str[i]=='*'||str[i]=='/'||str[i]=='%'){
r=i;
break;
}
}
stringstream stream;
if(r==str.size()-1){
stream<<str;
stream>>c;
return c;
}
stream<<str.substr(r+1);
stream>>c;
switch(str[r]){
case '*':
return tdm(str.substr(0,r))*c;
case '/':
return tdm(str.substr(0,r))/c;
case '%':
return tdm(str.substr(0,r))%c;
}
}
int pm(string str){//plus minus(time,divide and mod are included)
int i,r=str.size()-1,c;
for(i=str.size()-1;i>=0;i--){
if(str[i]=='+'||str[i]=='-'){
if(str[i-1]=='*'||str[i-1]=='/')break;//乘除負數
else if(str[i-1]=='+'||str[i-1]=='-'){//加減負數
if(str[i]==str[i-1]){
r=i;
str[r]='+';
break;
}
else{
r=i;
str[r]='-';
break;
}
}
else {
r=i;
break;
}
}
}
if(r==str.size()-1)return tdm(str);
c=tdm(str.substr(r+1));
if(str[r]=='+')return pm(str.substr(0,r))+c;
else return pm(str.substr(0,r))-c;
}
int cal(string str){//calculate
int i,r1=0,r2=0,c;
for(i=0;i<str.size();i++){
if(str[i]=='(')r1=i;
if(str[i]==')'){
r2=i;
break;
}
}
if(r1==0&&r2==0)return pm(str);
string temp=str.substr(r1+1,r2-r1-1);
c=pm(temp);
string cstr;
stringstream stream;
stream<<c;
stream>>cstr;
return cal(str.substr(0,r1)+cstr+str.substr(r2+1));
}
int main(){
string str;
while(getline(cin,str)){
cout<<cal(str)<<endl;
}
return 0;
}