#include<iostream>
#include<cstring>
using namespace std;
int term();
int expr();
int factor();
int expr()
{
int result = term();
bool more = true;
while(more)
{
char c = cin.peek();
if(c == '+' || c == '-')
{
cin.get();
int value = term();
if(c == '+')
result += value;
else if(c == '-')
result -= value;
}
else more = false;
}
return result;
}
int term()
{
int result = factor();
bool more = true;
while(more)
{
char c = cin.peek();
if(c == '*' || c == '/')
{
cin.get();
int value = factor();
if(c == '*')
result *= value;
else
result /= value;
}
else
more = false;
}
return result;
}
int factor()
{
int result = 0;
char c = cin.peek();
if(c == '(')
{
cin.get();//去掉左括号
result = expr();
cin.get();//去掉右括号
}
else
{
while(isdigit(c))
{
result = result*10 + c - '0';
cin.get();
c = cin.peek() ;
}
}
return result;
}
int main()
{
cout << expr() << endl;
//cout << term() << endl;
// cout << factor() << endl;
return 0;
}
还有一种方法是通过栈来实现,后面更新~