(7+6*4-12)/9怎么计算,采用C语言,如何制作程序?
2个回答
展开全部
typedef struct {
double v[100];
int op[100];
int n;
int pri;
char *s;
}Cur;
#define is_d(c) (c >= '0' && c <= '9')
void get_v(Cur* c) {
double v = 0;
double p = 1;
char* s = c->s;
while (*s) {
if (*s == '(') c->pri += 0x100;
else if (*s == ')') c->pri -= 0x100;
else if (is_d(*s)) {
if (p < 1) {
v += p * (*s -'0');
p *= 0.1;
}
else {
v = v*10 + (*s -'0');
}
}
else if (*s == '.') {
p = 0.1;
}
else break;
s++;
}
c->s = s;
c->v[c->n++] = v;
}
#define OP(m) (m & 0xF)
#define PRI(m) (m & (~0xF))
char op_c(int op) {
char a[] = " +-*/^ "; return a[OP(op)];
}
int get_o(Cur* c) {
while (*(c->s)) {
switch (*(c->s++)) {
case '+': return c->pri | 0x11;
case '-': return c->pri | 0x12;
case '*': return c->pri | 0x23;
case '/': return c->pri | 0x24;
case '^': return c->pri | 0x45;
}
}
return 0;
}
void _calc(Cur* c, int pri) {
while (c->n > 1) {
c->n--;
//printf("calc: %lf %c %lf\n", c->v[c->n-1], op_c(c->op[c->n]), c->v[c->n]);
switch(OP(c->op[c->n])) {
case 1: c->v[c->n-1] = c->v[c->n-1] + c->v[c->n]; break;
case 2: c->v[c->n-1] = c->v[c->n-1] - c->v[c->n]; break;
case 3: c->v[c->n-1] = c->v[c->n-1] * c->v[c->n]; break;
case 4: c->v[c->n-1] = c->v[c->n-1] / c->v[c->n]; break;
case 5: c->v[c->n-1] = pow(c->v[c->n-1], c->v[c->n]); break;
}
if (c->n > 1) {
if (PRI(c->op[c->n-1]) < pri) break;
}
}
}
double calc(char* s) {
Cur c;
int p1 = 0, p2;
c.pri = 0;
c.n = 0;
c.s = s;
get_v(&c);
while (*c.s) {
p2 = get_o(&c);
if (PRI(p1) >= PRI(p2)) {
_calc(&c, PRI(p2));
}
c.op[c.n] = p2;
p1 = p2;
get_v(&c);
}
_calc(&c, 0);
return c.v[0];
}
#define TEST(str) printf(#str " = %lf\n", calc(str))
int main() {
TEST("123.5789");
TEST("1+1");
TEST("2+1.25*(5+1)^2");
TEST("(7+6*4-12)/9");
TEST("12*(1+2*(3+(5+6)*7-4)+12-5*7+9)");
return 0;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
意法半导体(中国)投资有限公司
2023-06-12 广告
2023-06-12 广告
STM32F103R8T6是ST旗下的一款常用的增强型系列微控制器,是一款基于ARM Cortex-M内核的微控制器。STM32F103R8T6主要面向消费类电子产品、工业控制、医疗仪器、汽车电子等领域,可用于开发各种类型的应用。STM32...
点击进入详情页
本回答由意法半导体(中国)投资有限公司提供
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询