四则运算计算器——cpp

#include using namespace std; class Calc{ const char *str; int pos; public: Calc(const char *string) { str = string; pos = 0; int ret = addAndmis(divAndmut(eval())); cout << string << "=" << ret << endl; }Calc(const char *string, int val) { str = string; pos = 0; int ret = addAndmis(divAndmut(eval())); cout << (ret==val?"Succ":"Fail") << ":"<< string << "=" << ret << endl; }int addAndmis(int x) { if(str[pos]=='\0') { return x; }if(str[pos]=='+') { pos++; int y=divAndmut(eval()); cout << x << '+' << y << endl; x+=y; x = addAndmis(x); } else if(str[pos] == '-'){ pos++; int y=divAndmut(eval()); cout << x << '-' << y << endl; x-=y; x = addAndmis(x); } else { x=divAndmut(x); }return x; }int divAndmut(int x) { if(str[pos]=='\0') { return x; }if(str[pos]=='*') { pos++; int y=eval(); cout << x << '*' << y << endl; x*=y; x = divAndmut(x); } else if(str[pos] == '/') { pos++; int y=eval(); cout << x << '/' << y << endl; if (y==0) { cout << "除数为0错误!" << endl; throw "除数为0错误!"; } x/=y; x = divAndmut(x); } else { return x; }return x; }int eval() { int x=0; if (str[pos]=='('){ pos++; x = eval(); x = addAndmis(x); if(str[pos]==')') { pos++; } else { cout << "运算表达式错误!" << endl; throw "运算表达式错误!"; }return x; } else if((str[pos]>='0' && str[pos]<='9')){ while(str[pos]>='0' && str[pos]<='9') x= 10*x+ str[pos++]-'0'; return x; }return x; } }; int main() { try { Calc a("1+2+3+4",10); // 连续计算 Calc a1("1*2*3*4",24); // 连续计算 Calc a2("(1+2)+3+4",10); // 连续计算 Calc a3("1+(2+3)+4",10); // 连续计算Calc b("3*(123+2)/3",125); // 括号,加减乘除运算 Calc b1("3*(123+2)/5/3",25); // 括号,加减乘除运算 Calc b2("1*2+3*4",14); // 括号,加减乘除运算Calc z("3*(123+2)/0"); // 触发除数为0 异常 }catch (...){}return 0; }

【四则运算计算器——cpp】1+2
3+3
6+4
Succ:1+2+3+4=10
1*2
2*3
6*4
Succ:1*2*3*4=24
1+2
3+3
6+4
Succ:(1+2)+3+4=10
2+3
1+5
6+4
Succ:1+(2+3)+4=10
123+2
3*125
375/3
Succ:3*(123+2)/3=125
123+2
3*125
375/5
75/3
Succ:3*(123+2)/5/3=25
1*2
3*4
2+12
Succ:1*2+3*4=14
123+2
3*125
375/0
除数为0错误!

    推荐阅读