第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;
}本回答被提问者采纳