用C语言编一个能运算任何四则用算的程序 (和数据结构有关)
解决时间 2021-07-19 03:06
- 提问者网友:浮克旳回音
- 2021-07-18 12:59
例子:6-8/4+3*5@
9-6/(2+3)@
2*(3+5)/(6+4)@ 就向这样的例子 等等
请附是运行后的图片。 急!!!!!!!!!!!!!
最佳答案
- 五星知识达人网友:罪歌
- 2021-07-18 14:18
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char* next;
double opd[1000];
int opt;
double *popd = opd;
#define PUSH(n) { *popd++ = n; }
#define POP() (*--popd)
#define TOP() (*(popd-1))
#define EMPTY() (popd == opd)
#define SIZE() (popd - opd)
void fail(char* s)
{
printf("match '%s' failed near '%c'.\n", s, *--next);
exit(0);
}
#define lbr() { if(*next++ == '(') ; else fail("("); }
#define rbr() { if(*next++ == ')') ; else fail(")"); }
void term();
void lv1();
void lv2();
void cal(char);
void expr()
{
term(); lv1();
}
void term()
{
double num = 0;
if(isdigit(*next)) {
do {
num = num * 10 + (*next - '0');
} while(isdigit(*++next));
PUSH(num);
} else if(*next == '(') {
lbr(); expr(); rbr();
} else {
fail("term");
}
}
void lv1()
{
while(1) {
char c = *next;
if(c == '+' || c == '-') {
++next;
lv2(); ++opt; cal(c);
} else if(*next == '*' || *next == '/') {
lv2();
} else {
break;
}
}
}
void lv2()
{
while(1) {
char c = *next;
if(c == '*' || c == '/') {
++next;
term(); ++opt; cal(c);
} else if(isdigit(*next)) {
term();
} else {
break;
}
}
}
double eval(char* s)
{
static char buf[100];
char* p = buf;
while( *s != '@') {
if( *s != ' ' ) *p++ = *s;
++s;
}
next = buf;
expr();
if(*next || opt != 0) {
puts("invalid expression.");
exit(0);
}
return TOP();
}
void cal(char c)
{
double lhs, rhs, r;
if(SIZE() > 1) {
rhs = POP();
lhs = POP();
switch(c)
{
case '+': r = lhs + rhs; break;
case '-': r = lhs - rhs; break;
case '*': r = lhs * rhs; break;
case '/': r = lhs / rhs; break;
}
PUSH(r);
--opt;
}
}
int main()
{
char* expr[] = { "6-8/4+3*5@","9-6/(2+3)@","2*(3+5)/(6+4)@" };
int i;
for ( i = 0; i < 3; ++i )
printf("%s=%g\n", expr[i], eval( expr[i] ) );
return 0;
}
我要举报
大家都在看
推荐资讯