利用C++实现带括号的四则运算这里写自定义目录标题
基本思路是先处理乘除法,化成一个只有加减法的式子再处理加减法
遇到括号则递归 将括号内的内容算出一个值 将这个值代替括号带入原算式中
用两个stack分别保存 符号(signs)和 数字(number)(将字符串转化成int型储存)
每当有数字 be pushed into stack 则判断 signs stack最上端是不是* 或者/
#include <iostream>
#include <math.h>
#include <stack>
using namespace std;
int trans ( string );
int calculate ( string );
bool is_dig ( char c );
int is_bra ( char c );
bool is_signs ( char c );
int main ( void ){
using namespace std;
string s;
cin >> s;
cout << "计算结果是:";
cout << calculate( s ) << endl;
}
int trans ( string s ){
int i = s.length(), j;
int result = 0;
for ( char c : s ){
if ( c == '0' ) {
--j;
continue;
}
j = c - '0';
result += j * pow( 10, --i );
}
return result;
}
int calculate ( string s ){
stack<int> number;
stack<char> signs;
int start = 0, end = 0, size = s.length();
while ( end < size ){
if ( is_bra(s[start]) == 1 ){
int flag = 1;
for ( end = start + 1; end < size; ++end ){ // 这部分找到括号内的式子 进入递归
if ( is_bra(s[end]) == 1 ) flag++;
if ( is_bra(s[end]) == 2 ){
if ( --flag == 0 ){
break;
}
}
}
number.push( calculate ( s.substr ( start + 1, end-start - 1 ) ) );
start = ++end;
if ( !signs.empty() && signs.top() == '*' ){ // 当有数字被压入stack时判断符号stack最上面是不是乘除号 如果是 则运算
int n1 = number.top();
number.pop();
int n2 = number.top();
number.pop();
number.push( n1 * n2 );
signs.pop();
}
if ( !signs.empty() && signs.top() == '/' ){
int n1 = number.top();
number.pop();
int n2 = number.top();
number.pop();
number.push( n2 / n1 );
signs.pop();
}
continue;
}
else if ( is_signs( s[start] ) ){
signs.push( s[start] );
start++;
end++;
continue;
}
else {
for ( end = start; end < size; ++end ){
if ( !is_dig( s[end] ) ){
break;
}
}
number.push ( trans ( s.substr( start, end - start) ) );
start = end;
if ( !signs.empty() && signs.top() == '*' ){ // 当有数字被压入stack时判断符号stack最上面是不是乘除号 如果是 则运算
int n1 = number.top();
number.pop();
int n2 = number.top();
number.pop();
number.push( n1 * n2 );
signs.pop();
}
if ( !signs.empty() && signs.top() == '/' ){
int n1 = number.top();
number.pop();
int n2 = number.top();
number.pop();
number.push( n2 / n1 );
signs.pop();
}
}
}
stack<int> num2;
stack<char> sign2;
while ( !number.empty() ){
num2.push( number.top() ); // 这部分处理剩余的加减法
number.pop();
}
while ( !signs.empty() ){
sign2.push ( signs.top() );
signs.pop();
}
int ans = num2.top();
num2.pop();
while ( !sign2.empty() ){
if ( sign2.top() == '+' ){
ans += num2.top();
}
if ( sign2.top() == '-' ){
ans -= num2.top();
}
sign2.pop();
num2.pop();
} // 加减法处理完毕
return ans;
}
bool is_signs ( char c ){
if ( c == '+' || c == '-' || c == '*' || c == '/' ){
return true;
}
return false;
}
int is_bra ( char c ){
if ( c == '(' ){
return 1;
}
if ( c == ')' ){
return 2;
}
return 0;
}
bool is_dig ( char c ){
if ( c <='9' && c>= '0' ){
return true;
}
return false;
}