#define _crt_secure_no_warnings#include <stdio.h> #include <stdlib.h> #include <string.h>// Processing space void Delspace (char *str) {char *p1 = Str;char *P2 = Str;while ((*p1 = * (p2++)) = = ' + ') {if (*p1! = ') {p1++;}}} int isnum (char ch)//Determines whether the number {int is = 0;if (ch >= ' 0 ' && ch <= ' 9 ') {is = 1;} return is;} Get the string inside the parentheses char *mkh (char *str, int *pindex)//pair The parentheses to remove the contents of the parentheses {char *pstr = null;int num = 0;//record How many parentheses the logarithmic int leftindex = *pin Dex;do {switch (* (str+ (*pindex))) {case ' (': Num++;break;case ') ': if (0==num) {(*pindex) + +; Pstr = malloc (sizeof (char) * (*pindex-leftindex));//Allocate memory size strncpy_s (PSTR, *pindex-leftindex, str + leftindex, *pindex -leftindex-1); return pstr; } else {num--;//handles closing parenthesis}break;}} while (* (str+ (*pindex) + +)! = ') ';} Double Getnum (char *str, int *pindex) {Double value = 0.0;int index = *pindex;while (* (str+index) = = ' (') {char *psubstr = NUL L;*pindex = ++INDEX;PSUBSTR = MKH (str, piNdex);d ouble getValue (char *str); value = GetValue (PSUBSTR); free (psubstr);//release memory Psubstr = = Null;return value;} while (Isnum (* (str + index)))//str[index]{value = value * + (Str[index]-' 0 ');//character to integer index++;//move forward}if (* (str + index) == '.') {Double Xiaoshu = 1.0;while (isnum (* (str + ++index))//loop to non-digit after decimal point {Xiaoshu/= 10;//decimal Value + = xiaoshu* (* (str + index)-' 0 ');}} *pindex = Index;return value;} Double Getfirtnum (char *str, int *pindex) {Double value = 0.0;value = Getnum (str, pindex);//Gets a data while (1) {if (* (str + (*p index) = = ' * ') {(*pindex) ++;value *= getnum (str, pindex);//Calculate Multiplication}else if (* (str + (*pindex)) = = '/') {(*pindex) ++;value/= g Etnum (str, pindex);//calculate multiplication}else{break;}} return value;} Double GetValue (char *str) {Double value = 0.0;int index = 0;value = Getfirtnum (str, &index);//Gets First data while (1) {char ch = * (str + index);//Remove character index++;//loop traversal switch (CH) {case ' + ': return value;case ' + ': value + = Getfirtnum (str, &index); BR Eak;case '-': Value-= Getfirtnum (str, &index); Break;default: Break;}}} void Main () {printf ("Enter the expression to evaluate:"), char str[1024] = {0};scanf ("%[^\n]", str);d elspace (str);p rintf ("\ n evaluates expression value =%f\n", GetValue (str)); system ("Pause");}
Test results:
Copyright NOTICE: This article is for bloggers original article, welcome to point out the code is bad, and put forward the Code optimization scheme. Welcome guidance, Night code, desperately struggling to update in ...
Compiler principle: Implement advanced Expression evaluator (beginner)