#include "stdafx.h"
#include
#include "stack"
#include
#include
#include
using namespace std;
void Show(char *szShow);
bool IsOperator(char pValue);
float Calculate(float fFirst, float fSecond, char cOperator);
bool IsOperator(char pValue);
float Calculate(float fFirst, float fSecond, char cOperator);
int _tmain(int argc, _TCHAR* argv[])
{
char szData[128]; //準備運算的字串
sprintf(szData, "30 4 / 4 9 + 6 3 - * 4 * - 100 +"); //隨便一串資料
char split[4] = " ", *token; //分割字串需要的參數
stack stackData;
float fTemp = 0, fFirst = 0, fSecond = 0;
char szBuff[64]; //顯示用
stack stackData;
float fTemp = 0, fFirst = 0, fSecond = 0;
char szBuff[64]; //顯示用
token = strtok(szData, split);
//將資料分割
while(token != NULL)
{
//確認是否為運算符號
if (IsOperator(*token))
{
//確認stack裡的資料足夠
if (stackData.size() < 2)
{
break;
}
while(token != NULL)
{
//確認是否為運算符號
if (IsOperator(*token))
{
//確認stack裡的資料足夠
if (stackData.size() < 2)
{
break;
}
//將資料從stack中讀出
fSecond = stackData.top();
stackData.pop();
fFirst = stackData.top();
stackData.pop();
fSecond = stackData.top();
stackData.pop();
fFirst = stackData.top();
stackData.pop();
//進行運算
fTemp = Calculate(fFirst, fSecond, *token);
fTemp = Calculate(fFirst, fSecond, *token);
//將數字丟到stack中
stackData.push(fTemp);
}
else
{
//將數字丟到stack中
fTemp = atof(token);
stackData.push(fTemp);
}
token = strtok(NULL, split);
}
}
//輸入字串錯誤
if (stackData.size() != 1)
{}
else
{
fTemp = stackData.top();
if (stackData.size() != 1)
{}
else
{
fTemp = stackData.top();
sprintf(szData, "The answer is %.2f\r\n", fTemp);
printf(szData);
}
}
system("pause");
return 0;
}
void Show(char *szShow)
{
printf(szShow);
}
{
printf(szShow);
}
bool IsOperator(char pValue)
{
if (pValue == '+' ||
pValue == '-' ||
pValue == '*' ||
pValue == '/')
return true;
{
if (pValue == '+' ||
pValue == '-' ||
pValue == '*' ||
pValue == '/')
return true;
return false;
}
}
float Calculate(float fFirst, float fSecond, char cOperator)
{
switch(cOperator)
{
case '+':
return fFirst + fSecond;
break;
case '-':
return fFirst - fSecond;
break;
case '*':
return fFirst * fSecond;
break;
case '/':
return fFirst / fSecond;
break;
default:
break;
}
return 0;
}
{
switch(cOperator)
{
case '+':
return fFirst + fSecond;
break;
case '-':
return fFirst - fSecond;
break;
case '*':
return fFirst * fSecond;
break;
case '/':
return fFirst / fSecond;
break;
default:
break;
}
return 0;
}
沒有留言:
張貼留言