把字符串解析成常量表达式
- 试图把输入的字符串转换成能够计算的数学表达式;
- 设计模式:审批模式;
- 优先级:’()’ > ‘*/’ > ‘±’;
- 解析字符串:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int isnum(char ch);
void eatspace(char *str);
char * roundbmatch(char *str, int *pindex);
double getnum(char *str, int *pindex);
double plus(char *str);
double multi(char *str, int *pindex);
int isnum(char ch) {
return (ch >= '0'&&ch <= '9') ? 1 : 0;
}
void eatspace(char *str) {
char *p1 = str;
char *p2 = str;
while ((*p1 = *p2++) != '\0') {
if (*p1 != ' ')p1++;
}
}
char * roundbmatch(char *str, int *pindex) {
char *pstr = NULL;
int leftindex = *pindex;
int num = 0;
do {
switch (*(str + (*pindex))) {
case '(':
num++;
break;
case ')':
if (num == 0) {
(*pindex)++;
pstr = malloc(sizeof(char)*(*pindex - leftindex));
strncpy_s(pstr, *pindex - leftindex, str + leftindex, *pindex - leftindex - 1);
return pstr;
}
else {
num--;
}
break;
default:
break;
}
} while (*(str+ ++(*pindex)) != '\0');
}
double getnum(char *str,int *pindex) {
double value = 0.0;
int index = *pindex;
while (*(str + index) == '(') {
char *psubstr = NULL;
(*pindex)++;
psubstr = roundbmatch(str, pindex);
value = plus(psubstr);
free(psubstr);
return value;
}
while (1) {
while (isnum(*(str + index))) {
value = value * 10 + (*(str + index++) - 48);
}
if (*(str + index) == '.') {
double decimals = 1.0;
while (isnum(*(str + ++index))) {
decimals /= 10;
value += decimals * (*(str + index) - 48);
}
}
*pindex = index;
return value;
}
}
double plus(char *str) {
double value = 0.0;
int index = 0;
value = multi(str, &index);
while (1) {
char ch = *(str + index++);
switch (ch) {
case '\0':
return value;
case '+':
value += multi(str, &index);
break;
case '-':
value -= multi(str, &index);
break;
default:
break;
}
}
return value;
}
double multi(char *str, int *pindex) {
double value = 0.0;
int index = *pindex;
value = getnum(str, &index);
while (1) {
if (*(str + index) == '*') {
++index;
value *= getnum(str, &index);
}
else if (*(str + index) == '/') {
++index;
value /= getnum(str, &index);
}
else {
break;
}
}
*pindex = index;
return value;
}
void main() {
char str[100] = { 0 };
scanf("%[^\n]", str);
printf("输入%s\n", str);
eatspace(str);
printf("修正%s\n",str);
double value = plus(str);
printf("表达式结果值%f\n", value);
system("pause");
}
- 结果:多次测试结果表明正确。