C++实现带括号的四则运算
题目比较简洁:输入是一串由数字、运算符和括号组合的字符串。输出是这个算式的计算结果。
例如,输入是
"2 * (1 + 6) - (2 / 2) + 2 % 2"
输出是
13
本题我目前只考虑到了小括号的场景,无中括号[]和大括号{}的情况。
我用到的方法是:
- 将空格都去掉。
- 对无括号的四则运算,采用递归方法。中途还会判断每2个运算符之间的数据是否为纯数字,若含有非数字,则报错。
- 加上括号后,先在算式中找到最后一个"(“,以及其对应的”)"。复用1中的递归方法将其最后一个括号中的算式变成一个int类型的整数。
- 用while循环反复消除括号,最后剩下一个不带括号的字符串,跳出while循环。
- 将上述字符串带回1中,得到最终结果。
代码如下:
#include <stdio.h>
#include <vector>
#include <string>
#include <sstream>
std::vector<char> op_v = {'+', '-', '*', '/', '%'};
bool input_err = false;
void deletSpace(std::string& str)
{
while(str.find(' ') != str.npos)
{
str.erase(str.find(' '), 1);
}
}
int relizeOperation(std::string str)
{
for(char op : op_v)
{
int pos = str.find(op);
if(pos == str.npos)
{
if(op == op_v.back())
{
std::stringstream sin(str);
int i = 0;
sin >> i;
if(std::to_string(i) != str)
{
input_err = true;
}
return atoi(str.c_str());
}
continue;
}
switch(op)
{
case '+': return relizeOperation(str.substr(0, pos)) + relizeOperation(str.substr(pos + 1));
break;
case '-': return relizeOperation(str.substr(0, pos)) - relizeOperation(str.substr(pos + 1));
break;
case '*': return relizeOperation(str.substr(0, pos)) * relizeOperation(str.substr(pos + 1));
break;
case '/': return relizeOperation(str.substr(0, pos)) / relizeOperation(str.substr(pos + 1));
break;
case '%': return relizeOperation(str.substr(0, pos)) % relizeOperation(str.substr(pos + 1));
break;
dafault: printf("error\n");
break;
}
}
return -1;
}
int main(int argc, char* argv[])
{
std::string test_str = " 2*(1+6)- (2/2) + 2%2";
deletSpace(test_str);
printf("input string is %s\n", test_str.c_str());
int temp_res = 0;
int lpos = test_str.find_last_of('(');
int rpos = test_str.find(')', lpos);
std::string sub_str = "";
while(lpos != test_str.npos)
{
sub_str = test_str.substr(lpos + 1, rpos - lpos - 1);
temp_res = relizeOperation(sub_str);
test_str = test_str.substr(0, lpos) + std::to_string(temp_res) + test_str.substr(rpos + 1);
lpos = test_str.find_last_of('(');
rpos = test_str.find(')', lpos);
}
int resault = relizeOperation(test_str);
printf("resault is %d\n", resault);
if(input_err == true){printf("error! please check your input!\n");}
return 0;
}
程序执行结果是:
PS C:\Users\zhanghao\Downloads\code\exercise> g++ .\四则运算.cpp
PS C:\Users\zhanghao\Downloads\code\exercise> .\a.exe
input string is 2*(1+6)-(2/2)+2%2
resault is 13