224-m-Basic Calculator

int calculate(char* s) {
int result = 0;
int n = 10240;
int numstack[n];
char operastack[n];
memset(numstack, 0, sizeof(int) * n);
memset(operastack, 0, sizeof(char) * n);
char *sp = s;
char *nums = "1234567890";
char *operas = "(+-";
char *plusMinus = "+-";
char left = '(', right = ')';

int num = 0;
int indexn = 0, indexo = 0;
bool isKuohao = false;
while (*sp != '\0') {
if (strchr(nums, *sp)) { //操作数入栈
while (strchr(nums, *sp) && *sp != '\0') {
num = num * 10 + *sp - '0';
sp++;
}
numstack[indexn] = num;
indexn++;
if (indexn > 1 && strchr(plusMinus, operastack[indexo - 1])) { //操作数大于1且操作栈最后一个是可运算符则直接运算
int temp = 0;
if (operastack[indexo - 1] == '+')
temp = numstack[indexn - 1] + numstack[indexn - 2];
else
temp = numstack[indexn - 2] - numstack[indexn - 1];
numstack[indexn - 2] = temp;
indexn--;
indexo--;
}
}
if (strchr(operas, *sp) && *sp != '\0') { //操作符入栈
num = 0;
operastack[indexo] = *sp;
indexo++;
if (indexo > 1 && strchr(plusMinus, operastack[indexo - 1]) && strchr(plusMinus, operastack[indexo - 2])) {
//连续两个为可操作符时则计算前一个
int temp = 0;
if (operastack[indexo - 2] == '+')
temp = numstack[indexn - 1] + numstack[indexn - 2];
else
temp = numstack[indexn - 2] - numstack[indexn - 1];
numstack[indexn - 2] = temp;
indexn--;
operastack[indexo - 2] = operastack[indexo - 1];
indexo--;
}
}
if (*sp == right) { //遇到右括号,则退栈运算
if (operastack[indexo - 1] == '(')
indexo--;
else
{
int tempn = 0;
char tempo = operastack[indexo - 1];
if (tempo == '+')
tempn = numstack[indexn - 2] + numstack[indexn - 1];
else
tempn = numstack[indexn - 2] - numstack[indexn - 1];
numstack[indexn - 2] = tempn;
indexn--;
indexo -= 2;
}
isKuohao = true;
}
sp++;
}
if (isKuohao && indexo > 0) {
char tempo = operastack[0];
if (tempo == '+')
numstack[0] = numstack[0] + numstack[1];
else if (tempo == '-')
numstack[0] = numstack[0] - numstack[1];
}
result = numstack[0];

return result;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：224-m-Basic Calculator 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)