Question: A string represents a four-character arithmetic expression, and the correct value of this expression must be calculated. Note: 1. The four arithmetic operations are addition, subtraction, multiplication, division, and "+-*/" 2. the number in this expression can only be one digit (the value range is 0 ~ 9) 3. In addition, if there is a case that division cannot be performed, perform the following round-down operation. For example: 8/3, the value is 2. For example, if there is a string "8 + 7*2-9/3", its value is 19. The Code is as follows:
#include "stdafx.h"#include <stdio.h>#include <string.h>#include <assert.h>int cal(int nNum1, char op, int nNum2){if(op == '+') {return nNum1 + nNum2;}if(op == '-'){return nNum1 - nNum2;}if(op == '*'){return nNum1 * nNum2;}if(op == '/'){return nNum1 / nNum2;}}int calculate(int len, char *expstr){assert(expstr);if(len < 3){return -1;}char *p = expstr;int nNum1 = p[0] - '0';char op = p[1];int nNum2 = p[2] - '0';p += 3;while(*p){if(*p=='*' || *p=='/'){nNum2 = cal(nNum2, *p, p[1]-'0');}else{nNum1 = cal(nNum1, op, nNum2);op = *p;nNum2 = p[1] - '0';}p += 2;}return cal(nNum1, op, nNum2);}int main(){//char str[] = "1+2*3/5-6*7";char str[] = "8+7*2-9/3";int res = calculate(strlen(str), str);printf("result: %d\n", res);}