Implementation of string arithmetic operations

Source: Internet
Author: User

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);}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.