[问题描述] 一个算术表达式是由操作数(operand)、运算符(operator)和界限符(delimiter)组成的。假设操作数

[问题描述]
一个算术表达式是由操作数(operand)、运算符(operator)和界限符(delimiter)组成的。假设操作数是正整数,运算符只含加减乘除等四种运算符,界限符有左右括号和表达式起始、结束符“#”,如:#(7+15)*(23-28/4)#。引入表达式起始、结束符是为了方便。编程利用“算符优先法”求算术表达式的值。
[基本要求]
(1) 从键盘读入一个合法的算术表达式,输出正确的结果。
(2) 显示输入序列和栈的变化过程。
[选作内容]
(1) 扩充运算符集合。
(2) 引入变量操作数。
(3) 操作数类型扩充到实数。

第1个回答  2010-12-24
#include <stdio.h>
#include <math.h>
enum state
;
int ctoi( char c)
bool isNum( char a)
bool isOp(char op)
{
switch(op)
{
case '+':
return true;
break;
case '-':
return true;
break;
case '*':
return true;
break;
case '/':
return true;
break;
default:
return false;
break;
}
}
bool isDot(char dot)
int checkString( char str[], double *a, double * b, char* op, int num)
{
enum state s = BEGIN;
int a_i = 0;
int b_i = 0;

double num1 = 0;
double num2 = 0;
int pointNum = 0;
for( int i = 0; i < num; ++i)
{
if(str[i] == ' ')continue;
switch(s)
{
case BEGIN:
if(isNum(str[i]))

elses = ERROR;
break;
case P2:
if(isNum(str[i]))

else if(isDot(str[i]))
{
s = P3;
}
else if(isOp(str[i]))
{
*op = str[i];
s = P5;
}
else
s = ERROR;
break;
case P3:
if(isNum(str[i]))
{
num1 = num1 + ctoi(str[i]) * pow(0.1, ++pointNum) ;
s = P4;
}
else
s = ERROR;
break;
case P4:
if(isNum(str[i]))
{
num1 = num1 + ctoi(str[i]) * pow(0.1, ++pointNum);
s = P4;
}
else if(isOp(str[i]))
{
*op = str[i];
s = P5;
}
else
s = ERROR;
break;
case P5:
if(isNum(str[i]))
{
num2 = num2 * 10 + ctoi(str[i]);
s = P6;
}
else
s = ERROR;
break;
case P6:
pointNum = 0;
if(isNum(str[i]))
{
num2 = num2 * 10 + ctoi(str[i]);
s = P6;
}
else if(isDot(str[i]))
{
s = P7;
}
else
s = END;
break;
case P7:
if(isNum(str[i]))
{
num2 = num2 + ctoi(str[i]) * pow(0.1, ++pointNum);
s = P8;
}
else
s = END;
break;
case 8:
if(isNum(str[i]))
{
num2 = num2 + ctoi(str[i]) * pow(0.1, ++pointNum);
s = P8;
}
else if(isOp(str[i]))
{
s = END;
}
else
s = END;
break;
case ERROR:
printf("express error. \n");
break;
}
if (s == END || s == ERROR)
break;
}
if(s==END)
else
}
int main()
{
char op;
double a;
double b;

char string[128] = ;
scanf("%s", &string);
printf("the expression you input is : %s. \n", string);
getchar();

if (-1 == checkString(string, &a, &b, &op, 128))
{
printf("error occur while checking expression. Be sure no space in your expression when input\n");
getchar();
return 0;
}

double result;
switch(op)
{
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
if(b != 0)
result = a / b;
else
{
printf(" error! %d/%d", a, b);
return -1;
}
break;
default:
printf("undefined expression.\n");
break;
}

printf("%f %c %f = %f\n", a, op, b, result);
return 0;
}本回答被提问者采纳

Warning: Invalid argument supplied for foreach() in /www/wwwroot/aolonic.com/skin/templets/default/contents.html on line 45
相似回答