Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize the Operation of Mathematical expression in C language

Shulou Source: shulou.com Published: 2022-06-02 10:20:51 10月03日 Update

In order to solve this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

You have shared the specific code of C language to realize the operation of mathematical expressions, the specific contents are as follows

1. Development ideas: (fake expression 2 * 3 * (1 + 2))

The numbers should be taken out and put in memory one by one. According to the adjacent two calculation symbols, it is judged whether to take out the numbers for calculation, and the calculated values of the two numbers are replaced in memory and placed sequentially. Consider using stack as a data structure to save numbers and symbols, using 2 stacks, 1 stack to save numbers, and one stack to save operation symbols.

2. In order to use the data structure of stack, this code is developed in pure C language, so write the code of stack first, refer to:

Implementation of general data structure in C language (3): general vertebral stack

3. Important processing logic

(1) how to judge the precedence relationship between the two operators

(2) how to convert characters into numbers

Because the content entered by the keyboard is a character type, it is necessary to judge the type of character input and make the necessary conversion.

ASCII code table, the header is: binary decimal hexadecimal characters

(3) how to judge the completion of expression processing

By default, a symbol # is preset, and the input content is 2 * 3 * (1 + 2) # when there is # in the symbol stack and the character currently processed is #. The expression is processed.

4. Code implementation

# define _ CRT_SECURE_NO_DEPRECATE#define _ CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1#include # include # include "myStack.h" / / determine whether the operator int ifOp (char c) {switch (c) {case'+': return 1; case'-': return 1; case'*': return 1; case'/': return 1; case'(': return 1) Case')': return 1; case'#': return 1; default: break;} return 0;} int findOffset (char * str,char c len) {for (int I = 0; I

< len;i++) { if (str[i] == c) { return i; } } return -1;}//判断任意相继出现的2个运算符的优先级char yxji(char op1,char op2) { char ops[] = "+-*/()#"; char oplist[7][7] = { ">

> "," > "," > "

Tags: Expressions operations numbers codes symbols languages variables addresses characters content pointers processing development input mathematics data data structures structures problems no Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information NVidia Docker Shulou Tech Info Redmi