一看二做三总结
分类: C/C++
2011-05-14 19:12:39
// 利用tdd开发方法实现的四则混合程序
#include
#include
#include
#include
#include "calc.h"
#define LEVEL_MAX 2
struct StrInfo
{
char *head;
int pos;
};
char Op[LEVEL_MAX][2] =
{
{'+', '-'},
{'*', '/'}
};
int CalcValue(int a, int b, char op)
{
switch(op)
{
case '+': return (a + b);
case '-': return (a - b);
case '*': return (a * b);
case '/': return (a / b);
default: break;
}
assert(0);
return 0;
}
int num1(StrInfo *strinfo)
{
int result=0;
result = *(strinfo->head + strinfo->pos) - '0';
strinfo->pos--;
return result;
}
char GetOperator(StrInfo *strinfo, int level)
{
char ret = 0;
ret = *(strinfo->head + strinfo->pos);
if ((Op[level][0] == ret) ||
(Op[level][1] == ret))
{
strinfo->pos--;
return ret;
}
return 0;
}
int Calc(StrInfo *strinfo, int level)
{
int a, b, result=0;
char op;
if (level==1)
{
if (')' == *(strinfo->head + strinfo->pos))
{
strinfo->pos--;
a = Calc(strinfo, 0);
strinfo->pos--;
}
else
{
a = num1(strinfo);
}
}
else
{
a = Calc(strinfo, level+1);
}
op = GetOperator(strinfo, level);
if (0 == op)
{
return a;
}
b = Calc(strinfo, level);
result = CalcValue(b, a, op);
return result;
}
int StrInfoInit(StrInfo *strInfo, char *str)
{
strInfo->head = str;
strInfo->pos = strlen(str)-1;
return 0;
}
// main func
int calc(char *str)
{
StrInfo strInfo;
int result;
StrInfoInit(&strInfo, str);
result = Calc(&strInfo, 0);
printf("calc = %d \n",result);
return result;
}