回复:(雨中飞燕)以下是引用夜火在2007-9-18 12:11:...
大姐,小弟知错了.
我自己编了一个,但得不到正确结果.相烦指教.
#include "stdio.h"
float Add(float a,float b)
{
float c;
c = a + b;
return c;
}
float Sub(float a,float b)
{
float c;
c = a - b;
return c;
}
float Mul(float a,float b)
{
float c;
c = a * b;
return c;
}
float Div(float a,float b)
{
float c;
c = a / b;
return c;
}
float Input()
{
printf("请输入您要计算的四则运算表达式(表达式中最多有3个运算符,数据范围为1-100的整数)\n");
char c;
char Space[20];
c = getchar();
int d; //用于记录表达式的长度
for (int i = 0;c != '\n';i++)
{
Space[i] = c;
c = getchar();
d = i+1;
}
int a;
int Num = 0; //用于表示运算符的个数
int a1,a2,a3; //用于表示3个运算符
int j = 0,k = 0;
int op,op1,op2,op3,op4,op5[8],op6; //用于保存操作数
a = (int)Space[0];
for ( i = 0;i < d;i++)
{
if (k ==1)
{
op = op*10+a-48;
}
if (k ==2)
{
op = op*10+a-48;
}
op = a - 48;
if (a < 48)
{
op5[j] = op;
j++;
k = 0;
Num++;
switch(j)
{
case 1:
a1 = a;
op1 = op5[0];
break;
case 2:
a2 = a;
op2 = op5[1];
break;
case 3:
a3 = a;
op3 = op5[2];
break;
}
}
else
{
k++;
}
a = (int)Space[i+1];
}
a = (int)Space[d-1];
op6 = a - 48;
a = (int)Space[d-2];
if (a > 48)
{
op6 = (a-48)*10+op6;
a = (int)Space[d-3];
if (a>48)
{
op6 = (a-48)*10+op6;
}
}
switch(Num)
{
case 1: //一个运算符
switch(a1)
{
case 43:
return Add((float)op1,(float)op6);
break;
case 45:
return Sub((float)op1,(float)op6);
break;
case 42:
return Mul((float)op1,(float)op6);
break;
case 47:
return Div((float)op1,(float)op6);
break;
}
break;
case 2: //二个运算符
switch(a1)
{
case 43:
switch(a2)
{
case 43:
return Add(Add((float)op1,(float)op2),(float)op6);
break;
case 45:
return Sub(Add((float)op1,(float)op2),(float)op6);
break;
case 42:
return Add((float)op1,Mul((float)op2,(float)op6));
break;
case 47:
return Add((float)op1,Div((float)op2,(float)op6));
break;
}
break;
case 45:
switch(a2)
{
case 43:
return Add(Sub((float)op1,(float)op2),(float)op6);
break;
case 45:
return Sub(Sub((float)op1,(float)op2),(float)op6);
break;
case 42:
return Sub((float)op1,Mul((float)op2,(float)op6));
break;
case 47:
return Sub((float)op1,Div((float)op2,(float)op6));
break;
}
break;
case 42:
switch(a2)
{
case 43:
return Add(Mul((float)op1,(float)op2),(float)op6);
break;
case 45:
return Sub(Mul((float)op1,(float)op2),(float)op6);
break;
case 42:
return Mul(Mul((float)op1,(float)op2),(float)op6);
break;
case 47:
return Div(Mul((float)op1,(float)op2),(float)op6);
break;
}
break;
case 47:
switch(a2)
{
case 43:
return Add(Div((float)op1,(float)op2),(float)op6);
break;
case 45:
return Sub(Div((float)op1,(float)op2),(float)op6);
break;
case 42:
return Mul(Div((float)op1,(float)op2),(float)op6);
break;
case 47:
return Div(Div((float)op1,(float)op2),(float)op6);
break;
}
break;
}
break;
case 3: //三个运算符
break;
}
return 0;
}
int main()
{
printf("%ld",(long)Input());
}