恩,最近對sourceforge.net失望了,不如參考novus大大的來改,
在psdn看到也有結構清楚的,但廢碼太多,不如novus大大來的簡潔有力!
// design by novus 2009
// some right reserved
// design by 天亮damody 2009
// 隨便抄吧!
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <cmath>
using namespace std;
double calculate(string s);
double Eval3(istream& iss);
double Eval2(istream& iss);
double Eval1(istream& iss);
double Eval0(istream& iss);
string redefine(string str,const char * a,const char * b);
int main() {
string input = "(x^2+3*y^2)*e(-x^2-y^2)";
string tmp;
char strx[100],stry[100];
/*cin >> input;*/ //輸入公式
//印出一個面的值,準備來畫3D了
for (double x = -2;x < 2;x +=0.1)
{
for (double y = 0;y < 1;y +=0.1)
{
sprintf(strx,"(%lf)",x);
sprintf(stry,"(%lf)",y);
tmp = redefine(input,"x",strx);
tmp = redefine(tmp,"y",stry);
printf("%2.2lf ",calculate(tmp));
}
cout << endl;
}
//一般的運算
//直到按q才離開
for (cin >> input;input != "q";cin >> input)
{
cout << calculate(input) << endl;
}
system("pause");
}
//前置字串處理器
double calculate(string s)
{
istringstream iss;
s = redefine(s,"sin","s");
s = redefine(s,"cos","c");
s = redefine(s,"tan","t");
s = redefine(s,"exp","e");
s = redefine(s,"e^","e");
//cout << s << endl;
iss.str(s);
return Eval0(iss);
}
//前置字串處理函數
string redefine(string str,const char *a,const char *b)
{
for (;string::npos != str.find(a);)
{
str.replace(int(str.find(a)),strlen(a),b,strlen(b));
}
return str;
}
//優先權愈高愈先算
//優先權3的運算
double Eval3(istream& iss) {
double Eval0(istream& iss);
double res=0;
if (iss.peek() == '(' && iss.get()) {
res = Eval0(iss);
iss.peek() == ')' && iss.get();
} else if (iss.peek() == 's' && iss.get())
res = sin(Eval2(iss)/180*4*atan(1));
else if (iss.peek() == 'c' && iss.get())
res = cos(Eval2(iss)/180*4*atan(1));
else if (iss.peek() == 't' && iss.get())
res = tan(Eval2(iss)/180*4*atan(1));
else if (iss.peek() == 'e' && iss.get())
res = exp(Eval2(iss));
else {
iss >> res;
}
return res;
}
//優先權2的運算
double Eval2(istream& iss) {
double res = Eval3(iss);
if (iss.peek() == '^' && iss.get())
res = pow(res,Eval2(iss));
return res;
}
//優先權1的運算
double Eval1(istream& iss) {
double res = Eval2(iss);
while (iss.peek() == '*' || iss.peek() == '/')
(iss.get() == '*')? (res*=Eval2(iss)): (res/=Eval2(iss));
return res;
}
//優先權0的運算
double Eval0(istream& iss) {
double res = Eval1(iss);
while (iss.peek() == '+' || iss.peek() == '-')
res +=(iss.get() == '+')? Eval1(iss): -Eval1(iss);
return res;
}
全站熱搜
留言列表