예제 #1
0
void calc(SS& oprs, SD& nums, string& s) {
	string opr = oprs.top(); oprs.pop();
	if (opr[0] == 'u') s += opr[1];
	else s += opr;
	s += ' ';
	
	double b = nums.top(); nums.pop();
	if (opr[0] == 'u' || (is_func(opr) && opr != "pow")) {
			 if (opr == "u+") nums.push(b);
		else if (opr == "u-") nums.push(-b);

		else if (opr == "sin") nums.push(sin(b));
		else if (opr == "cos") nums.push(cos(b));
		else if (opr == "exp") nums.push(exp(b));
		else if (opr == "log") nums.push(log(b));
		else if (opr == "sqrt") nums.push(sqrt(b));
		else if (opr == "fabs") nums.push(fabs(b));
		return;
	}

	double a = nums.top(); nums.pop();
		 if (opr == "*") nums.push(a * b);
	else if (opr == "+") nums.push(a + b);
	else if (opr == "-") nums.push(a - b);
	else if (opr == "pow") nums.push(pow(a, b));
}
예제 #2
0
void play(MSI& rank, VS& toks) {
	SS oprs;
	SD nums;
	string out = "";
	char str[100];

	cout << "# from infix to postfix!!!" << endl;
	
	for (VS::iterator i = toks.begin(); i != toks.end(); i++) {
		string tok = *i;
		
		cout << "There is a " << tok << ": ";

		if (is_num(tok)) {
			cout << "push to output" << endl;
			sprintf(str, "%.6lf ", stod(tok));
			out += str;
			nums.push(stod(tok));
		}
		else if (tok == ",") {
			cout << "flush the stack until '('" << endl;
			while (oprs.top() != "(")
				calc(oprs, nums, out);
		}
		else if (tok == ")") {
			cout << "flush the stack until '(' and check if there's a func" << endl;
			while (oprs.top() != "(")
				calc(oprs, nums, out);
			oprs.pop();
			if (!oprs.empty() && is_func(oprs.top()))
				calc(oprs, nums, out);
		}
		else {
			cout << "push to stack" << endl;
			if ( is_unary(tok) && (i == toks.begin() || rank[*(i - 1)] > 0) )
				oprs.push("u" + tok);
			else { 
				while (!is_func(tok) && tok != "(" && !oprs.empty() && rank[oprs.top()] <= rank[tok]) {
					cout << "\t*** stack.top() has higher precedence" << endl;
					calc(oprs, nums, out);
				}
				oprs.push(tok);
			}
		}

		cout << "\tcurrent output: " << out << endl
			 << "\tcurrent  stack: " << oprs << endl;
	}

	while (!oprs.empty())
		calc(oprs, nums, out);

	cout << "There is nothing left, so flush the stack to output" << endl
		 << "\tcurrent output: " << out << endl
		 << "#transformation completed!!!" << endl
		 << "Postfix Exp: " << out << endl
		 << "RESULT: " << nums.top() << endl << endl;
}