計算器 - 棧的實現(xiàn)

/**//////////////////////////////////////////////////////////////
// File Name : calculator.cpp
/**//////////////////////////////////////////////////////////////
// 本程序名為 計算器
//
// 小菜技術(shù)有限,程序難免有不足和錯誤,望各位高手多多指教
// 編程序的時間緊促,功能不全,今后會加以改進
// 小菜的QQ:414112390 Q群:7196588
// Make By : Cedric Porter [Stupid ET] ~華肥~
/**//////////////////////////////////////////////////////////////
#include <iostream>
#include <stack>
#include <list>
#include <cmath>
#define NDEBUG
using namespace std;
double toi(char*, int*);
int test(char);
stack<double, list<double> > num;
stack<char, list<char> > op;
int main()

{
op.push('\0');
char exp[100];
cin.getline(exp, 100, '\n');
int n = 0;
int len;
len = strlen(exp);
#ifndef NDEBUG
cout << exp << endl;
#endif 
while (exp[n] != '\0')
{
if (exp[n] == ' ')
{
for (int nn = n + 1;nn < len; nn++)
exp[nn-1] = exp[nn];
len--;
n--;
}
n++;
}
exp[len] = '\0';
#ifndef NDEBUG
cout << exp;
#endif 
int k;
k = 0;
int flag = 1;
char c;
c = exp[0]; 
while (flag)
{
if (c >= '0' && c <= '9' || c == '.')
num.push(toi(exp, &k));
else if (c == '(' || test(c) > test(op.top()))
{
op.push(c);
k++;
}
else if (c == '\0' && op.top() == '\0')
flag = 0;
else if (c == ')' && op.top() == '(')
{
op.pop();
k++;
}
else if (test(c) <= test(op.top()))
{
double y = num.top();
num.pop();
double x = num.top();
num.pop();
c = op.top();
op.pop();
switch (c)
{
case '*': x *= y; break;
case '/': x /= y; break;
case '+': x += y; break;
case '-': x -= y; break;
case '^': x = pow(x, y); break;
default : cout << "Error!!\n"; break;
}
num.push(x);
}
c = exp[k];
}
cout << endl << exp << " = " << num.top() << endl << endl;
system("pause");
return 0;
}
double toi(char* c, int* k)

{
double x, y = 1.0;
int flag = 1;
char s;
x = 0.0;
s = c[*k];
while (s >= '0' && s <= '9' || s == '.')
{
*k = *k + 1;
if (s >= '0' && s <= '9')
if (flag == 1)
x = 10*x + (s - 48);
else
{
y *= 0.1;
x += y * (s - 48);
}
else
flag = 0;
s = c[*k];
}
return (x);
}
int test(char c)

{
int x;
switch (c)
{
case '^' : x = 3; break;
case '*' : x = 2; break;
case '/' : x = 2; break;
case '+' : x = 1; break;
case '-' : x = 1; break;
case '(' : x = 0; break;
case ')' : x = 0; break;
case '\0' : x = -1; break;
}
return (x);
}

/**///////////////////////////////////////////////////
// 當(dāng)我打到這里時,我已經(jīng)經(jīng)過了n次吐血 
/**///////////////////////////////////////////////////
//
// 總結(jié):用Dev C++ 這個編譯器非常不爽,對代碼錯誤的
// 提示不足。這個程序的未知錯誤,Dev C++居然找不到。
// 姜還是老的辣,還是VC++ 糾錯能力強些
.
/**/////////////////////////////////////////////////// 



posted on 2009-08-13 11:32 Stupid ET 閱讀(1909) 評論(6) 編輯 收藏 引用 所屬分類: Language

