zoukankan      html  css  js  c++  java
  • 计算器类(C++&JAVA——表达式转换、运算、模板公式)

    运行:

    (a+b)*c
    后缀表达式:ab+c*
    赋值:
    Enter the a : 10
    Enter the b : 3
    Enter the c : 5
    结果为:65
    
    

    代码是我从的逻辑判断系统改过来的,可进行扩展或者修改 

    注意:1、适用变量为单字符。

               2、表达式不含空格

    PS:如果想让变量为多字符(字符串),那么变量与变量、变量与运算符之间应该用空格分开

    #include<iostream>
    #include<map>
    #include<string>
    #include<stack>
    #include<vector>
    using namespace std;
    class Logic {
    public:
    	Logic() {}                                      //构造函数
    	void Load(string);                                //input
    	int priority(char);                               //获取运算符优先级
    	string trans(string);                             //中缀式->后缀式
    	double calculate();    //逻辑判断
    	void V_assign();                                  //变量赋值
    	string M_exp;                            //中缀式
    	string P_exp;                            //后缀式
    	map<string, double> variate;               //赋值序列
    };
    void Logic::Load(string str) {
    	M_exp = str;;
    	P_exp = trans(M_exp);             //处理数据(表达式转换)
    }
    int Logic::priority(char ch) {
    	if (ch == '*'||ch=='/')
    		return 2;
    	if (ch == '+'||ch=='-')
    		return 1;
    	if (ch == '(')
    		return -1;
    	return 0;
    }
    double Logic::calculate() {
    	string operators("+-*/");
    	stack<double> res;            //此栈用作运算
    	double a, b;
    	for (int i = 0; i<P_exp.length(); i++) {
    		if (operators.find(P_exp[i]) == string::npos) {      //遇到操作数,根据“字典”翻译后入栈
    			res.push(variate[P_exp.substr(i, 1)]);
    		}
    		else {
    			switch (P_exp[i]) {
    			case '+':
    				a = res.top();
    				res.pop();
    				b = res.top();
    				res.pop();
    				res.push(a + b);
    				break;
    			case '*':
    				a = res.top();
    				res.pop();
    				b = res.top();
    				res.pop();
    				res.push(a * b);
    				break;
    			case '-':
    				a = res.top();
    				res.pop();
    				b = res.top();
    				res.pop();
    				res.push(b-a);
    				break;
    			case '/':
    				a = res.top();
    				res.pop();
    				b = res.top();
    				res.pop();
    				res.push(b/a);
    				break;
    			}
    		}
    	}
    	return res.top();
    }
    string Logic::trans(string m_exp) {
    	string p_exp;
    	stack<char> stk;
    	string operators("+-*/(");
    	for (int i = 0; i < m_exp.length(); i++) {
    		string one;
    		if (operators.find(m_exp[i]) != string::npos) {      //出现操作符
    			if (m_exp[i] == '(')         //栈中添加左括号
    				stk.push(m_exp[i]);
    			else {					    //操作符的优先级判断
    				while ((!stk.empty()) && (priority(m_exp[i]) <= priority(stk.top()))) {    //当栈不为空时,进行优先级判断
    					p_exp.push_back(stk.top());   //若当前操作符优先级低于栈顶,弹出栈顶,放到后缀式中
    					stk.pop();
    				}
    				stk.push(m_exp[i]);             //将当前操作符入栈
    			}
    		}
    		else if (m_exp[i] == ')') {            //出现右括号时,将栈中元素一直弹出,直至弹出左括号
    			while (stk.top() != '(') {
    				p_exp.push_back(stk.top());
    				stk.pop();
    			}
    			stk.pop();                         //弹出左括号
    		}
    		else {           //把操作数加入到后缀式中
    			variate[m_exp.substr(i, 1)] = 0;
    			p_exp.push_back(m_exp[i]);
    		}
    
    	}
    	while (!stk.empty()) {    //将栈中剩余操作符放到后缀式中
    		p_exp.push_back(stk.top());
    		stk.pop();
    	}
    	return p_exp;
    }
    void Logic::V_assign() {       //公式赋值
    	int i = 0;
    	for (auto it = variate.begin(); it != variate.end(); it++) {
    		cout << "Enter the " << it->first << " : ";
    		cin >> it->second;
    	}
    }
    int main() {
    	Logic my;
    	string str;
    	cin >> str;
    	my.Load(str);
    	cout << "后缀表达式:" << my.P_exp << endl;
    	cout << "赋值:" << endl;
    	my.V_assign();
    	cout<<"结果为:"<<my.calculate();
    	return 0;
    }
    
    

    JAVA: 

    import java.util.Scanner;
    public class Calculate {
        String m_exp=new String() ,p_exp=new String();
        int result=0;
        public Calculate(String exp) {
            m_exp=exp;
        }
        int counter(){
            int stk[]=new int[100],a,b;
            int top=-1;
            for(int i=0;i<p_exp.length();i++){
                if(p_exp.charAt(i)>='0'&&p_exp.charAt(i)<='9'){
                    stk[++top]=Character.getNumericValue(p_exp.charAt(i));
                }
                else{
                    switch (p_exp.charAt(i)) {
                    case '+':
                        a = stk[top--];
                        b = stk[top--];
                        stk[++top]=a+b;
                        break;
                    case '*':
                        a = stk[top--];
                        b = stk[top--];
                        stk[++top]=a*b;
                        break;
                    case '-':
                        a = stk[top--];
                        b = stk[top--];
                        stk[++top]=b-a;
                        break;
                    case '/':
                        a = stk[top--];
                        b = stk[top--];
                        if(a==0)
                            return 1;
                        stk[++top]=b/a;
                        break;
                    }
    
                }
            }
    
            if(top!=0)
                return 1;
            result=stk[0];
            return 0;
        }
        String trans(){
            char stk[]=new char[100];
            int top=-1;
            String operators=new String("+-*/(");
    
            for (int i = 0; i < m_exp.length(); i++) {
                if (operators.indexOf(m_exp.charAt(i)) != -1) {      //出现操作符
                    if (m_exp.charAt(i) == '(')         //栈中添加左括号
                        stk[++top]=m_exp.charAt(i);
                    else {                      //操作符的优先级判断
                        while ((top>=0) && (priority(m_exp.charAt(i)) <= priority(stk[top]))) {    //当栈不为空时,进行优先级判断
                            p_exp+=stk[top--];   //若当前操作符优先级低于栈顶,弹出栈顶,放到后缀式中
                        }
                        stk[++top]=(m_exp.charAt(i));             //将当前操作符入栈
                    }
                }
                else if (m_exp.charAt(i) == ')') {            //出现右括号时,将栈中元素一直弹出,直至弹出左括号
                    while (stk[top] != '(') {
                        p_exp+=stk[top--];
                    }
                    top--;                       //弹出左括号
                }
                else {           //把操作数加入到后缀式中
                    p_exp+=m_exp.charAt(i);
                }
    
            }
            while (top>=0) {    //将栈中剩余操作符放到后缀式中
                p_exp+=stk[top--];
            }
            return p_exp;
        }
        int priority(char ch){
            if (ch == '*'||ch=='/')
                return 2;
            if (ch == '+'||ch=='-')
                return 1;
            if (ch == '(')
                return -1;
            return 0;
        }
        public static void main(String []args){     //TEST
            Scanner input=new Scanner(System.in);
            Calculate my=new Calculate(input.next());       
            my.trans();         //后缀试转换
            if(my.counter()==1)
                System.out.println("ERROR");
            else
                System.out.println(my.result);
        }
    
    }
  • 相关阅读:
    把TXT GB2312文件转换成TXT UTF8文件
    把ANSI格式的TXT文件批量转换成UTF-8文件类型
    GB2312转换成UTF-8与utf_8转换成GB2312
    SQL 字符串处理函数大全
    编写一个程序,建立一个动态数组,为动态数组的元素赋值,显示动态数组的值并删除动态数组--简单
    设计一个使用常量成员函数的示范程序-简单
    声明一个复数类complex,使用友元函数add实现复数的加法-简单
    使用内联函数设计一个类,用来表示直角坐标系中的任意一条直线并输出它的属性
    设计一个点类point,再设计一个矩形类,矩形类使用point类的两个坐标点作为矩形的对角顶点,并可以输出4个坐标值和面积。使用测试程序验证程序。
    利用函数模板设计一人求数组元素总和的函数,并检验之-简单
  • 原文地址:https://www.cnblogs.com/F-itachi/p/9974342.html
Copyright © 2011-2022 走看看