Data structure and algorithm topic set (Chinese) 7-21 finding the value of prefix expression (25 points)

1. topic

Arithmetic expressions have the forms of prefix representation, infix representation and suffix representation. The prefix expression refers to the binary operator before two operands, for example, the prefix expression of 2 + 3 * (7-4) + 8 / 4 is: + + 2 * 3 - 7 4 / 8 4. Please design a program to evaluate the result value of the prefix expression.

Input format:

Input a prefix expression with no more than 30 characters in one line, only including +, -, *, / and operands, and separate different objects (operands and symbols) with spaces.

Output format:

Output the operation result of prefix expression, keep 1 decimal place, or ERROR message.

Input example:

+ + 2 * 3 - 7 4 / 8 4

Output example:

13.0

2. topic analysis

1. Calculation method: first, start to stack from right to left. When the first operator is encountered, the calculation result will be stacked twice, then the result will be stacked, and finally the total result will be output

Pit: the number may be a decimal or a negative number!!!!!!!!!!!!

2. Remember: the input is opposite, and the output is positive. In such cases, the stack can be used

3.atof uses the "include < cstdlib > header node"

4.getline(cin, list); / / note the writing method of entering one line at a time in C + +. The writing method needs to include < string > header files, but there will be line breaks

3. code

#include<iostream>
#include<stack>
#include<cstring>
#include<string>
#include<cstdio>
#Include < cstdlib > / / atof use
using namespace std;
int main()
{
	stack<double>st;
	string list;
	getline(cin, list);//Note that input one line at a time in C + +, which requires a header file
	double answer=0;
	for (int i = list.length()-1; i >= 0; i--)//Minus one because getline will get carriage return
	{
		char aaa = list[i];
		answer = 0;
		stack<char>templist;//Store entire string
		bool isnotoperator = false;
		while ((list[i] != ' ')&&(isdigit(list[i])||list[i]=='.'))
		{
			isnotoperator = true;
			templist.push(list[i]);//Put numbers on the temporary stack
			if (isdigit(list[i - 1]) || list[i - 1] == '.')//If there are numbers and decimal points in front of the stack
				i--;
			else
				break;

		}

		//char  number[31];
		//The char array was used at first. Later, it was found that a well-known error was the problem of initializing the array once it was used. If it is not handled, the number of this time may still have the last residue (70, 4.55 will remain). It is troublesome
		string number;
		while (!templist.empty())
		{
			//number[d++]=templist.top();
			 number=number+ templist.top();
			templist.pop();//Convert number to string
		}
		if (isnotoperator)//If the above has been converted into a number, the string will be converted into a double
		{
			double b = atof(number.c_str());
			if (list[i - 1] == '-'&&i>1)//If the front is - change it to a negative number
			{
				st.push(-b);//Negative
				i--;
			}
			else
				st.push(b);
		}
		if (list[i] != ' '&&!isdigit(list[i])&&isnotoperator==false)
		{
			double c, d;
			if (st.size() > 1)
			{
				 c = st.top(); st.pop();
				 d = st.top(); st.pop();
			}
			else//Handle the case where the entire expression has only one number
			{
				if (list[i] == '+')//E.g. + 9.234242
				{
					c = st.top(); st.pop();
					d = 0;
				}
				else if (list[i] == '-')//For example -9.234242
				{
					c = -1*st.top(); st.pop();
					d = 0;
				}
			}
			if (list[i] == '+')answer = answer + c + d;
			if (list[i] == '-')answer = answer + (c - d);
			if (list[i] == '*')answer = answer + (c*d);
			if (list[i] == '/')
			{
				if (d == 0) { cout << "ERROR" << endl; return 0; }//Direct output with divisor of 0
				else answer = answer + (c / d);
			}
			st.push(answer);
		}
	}
	if(st.size()!=1)cout<< "ERROR" << endl;//To prevent the whole formula from being nonstandard, but it doesn't seem to work 
	else printf("%.1f", st.top());
}
//+ + 2 * -20 - 7 4 / 8 4
//+ + -2.5 * 3.4 - 70 -4.5 / 8.3 4.2
//+123.434234











4. Fresh and clear version

(it's disgusting what I wrote on it https://blog.csdn.net/qq_41608020/article/details/80922359?utm_source=blogxgwz1)

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stack>
#include <string>
#include <cctype>
using namespace std;
stack <double> st;
int main()
{
	string s;
	getline(cin, s);
	for (int i = s.size() - 1; i >= 0; i--)
	{
		if (isdigit(s[i]))
		{
			double mul = 10, num = s[i] - '0';
			for (i--; i >= 0; i--)
			{
				if (isdigit(s[i]))
				{
					num += (s[i] - '0') * mul;
					mul *= 10;
				}
				else if (s[i] == '.')
				{
					num /= mul;
					mul = 1;
				}
				else if (s[i] == '-')
					num = -num;
				else
					break;
			}
			st.push(num);
		}
		else if (s[i] != ' ')   //else
		{
			double a, b, sum;
			a = st.top();
			st.pop();
			b = st.top();
			st.pop();
			switch (s[i])
			{
			case '+':
				sum = a + b;
				break;
			case '-':
				sum = a - b;
				break;
			case '*':
				sum = a * b;
				break;
			case '/':
			{
				if (b == 0)
				{
					cout << "ERROR";
					return 0;
				}
				sum = a / b;
			}
			}
			st.push(sum);
		}
	}
	printf("%.1lf", st.top());
}

 

Published 34 original articles, won praise 1, visited 216
Private letter follow

Added by rachybaby on Sat, 08 Feb 2020 11:09:24 +0200