2025年2月5日
四则运算实现
C++, 算法, 编程
0 Comments
实现简单的加减乘除四则运算
#include <iostream>
#include <stdio.h>
#include <string>
#include <stdlib.h>
using namespace std;
#include <stack>
/**
* 实现简单的四则运算器,支持加、减、乘、除四种运算。
*/
int calculate(string s){
stack<int> stk;
int num = 0;
char sign = '+';
for(int i = 0; i < s.size(); ++i) {
char c = s[i];
if (isdigit(c)) {
num = num * 10 + c - '0';
}
if (!isdigit(c) || i == s.size() - 1) {
switch (sign) {
int pre;
case '+': stk.push(num); break;
case '-': stk.push(-num); break;
case '*':
pre = stk.top();
stk.pop();
stk.push(pre * num);
break;
case '/':
pre = stk.top();
stk.pop();
stk.push(pre / num);
break;
}
sign = c;
num = 0;
}
}
int res = 0;
while (!stk.empty()) {
res += stk.top();
stk.pop();
}
return res;
}
int main() {
std::string s = "20+30*40-80";
int res = calculate(s);
cout << "res:" << res << endl;
system("pause");
return 0;
}
参考:https://mp.weixin.qq.com/s/ds0guq9gPTLIHLEQnFxZVQ