zoukankan      html  css  js  c++  java
  • 简单的表达式计算 c++


    1
    #include<iostream> 2 #include<stack> 3 #include<string> 4 #include<vector> 5 #include<map> 6 #include<algorithm> 7 using namespace std; 8 9 map<const char, int> priority;//用map来储存运算符的优先级 10 11 int compare(char a, char b){ 12 int cmp = 0; 13 if(b==')' && a=='(') cmp = 0; 14 else if(a=='(') cmp = -1; 15 else if(priority[a] < priority[b]) cmp = -1; 16 else if(priority[a] >= priority[b]) cmp = 1; 17 return cmp; 18 } 19 20 int cal(int a, int b, char op){ 21 int ans; 22 if(op=='+') ans = a+b; 23 else if(op=='-') ans = a-b; 24 else if(op=='*') ans = a*b; 25 else if(op=='/') ans = a/b; 26 return ans; 27 } 28 29 int calculator(){ 30 //根据优先级的关系,可以把他们的优先级定义为下面的形式 31 //个别运算符的优先级是与位置前后有关系的,需要特俗处理 32 priority['#'] = -1; 33 priority[')'] = 0; 34 priority['+'] = 1; 35 priority['-'] = 1; 36 priority['*'] = 2; 37 priority['/'] = 2; 38 priority['('] = 3; 39 cout<<"please input valid expression, enter to terminate..."<<endl; 40 char ch = getchar(); 41 stack<char> op; 42 stack<int> nums; 43 op.push('#'); 44 nums.push(0); 45 bool flag = true; 46 while(ch!='#' || op.top()!='#'){ 47 if(ch<='9' && ch>='0'){ 48 int number = 0; 49 while(ch>='0' && ch<='9'){//连续出现的数字看做一个整体 50 number = number*10 + (ch-'0'); 51 ch = getchar(); 52 } 53 // cout<<"number: "<<number<<endl; 54 // cout<<"op: "<<ch<<endl; 55 nums.push(number); 56 flag = true; 57 }else{//比较栈顶运算符和新输出运算符的优先级 58 int cmp = compare(op.top(), ch); 59 //cout<<"compare("<<op.top()<<","<<ch<<") = "<<cmp<<endl; 60 if(cmp==-1){//顶部优先级低时,把新的运算符压栈 61 op.push(ch); 62 flag = false; 63 ch = getchar(); 64 }else if(cmp==0){//即栈顶和新的运算符是'('和')',需要把'('弹出 65 op.pop(); 66 ch = getchar(); 67 }else if(cmp==1){//栈顶运算符优先级高的时候,就要进行运算 68 int num1, num2, tempans; 69 char tempop;//一定要注意num的顺序,否则会导致错误的运算结果 70 num2 = nums.top(); 71 nums.pop(); 72 num1 = nums.top(); 73 nums.pop(); 74 tempop = op.top(); 75 op.pop(); 76 tempans = cal(num1, num2, tempop); 77 //cout<<"tempans: "<<tempans<<endl; 78 nums.push(tempans); 79 } 80 if(ch=='-' && !flag) nums.push(0); 81 82 } 83 } 84 cin.get(); 85 return nums.top(); 86 } 87 int main(){ 88 int i = 10; 89 while(i--){ 90 cout<<calculator()<<endl; 91 } 92 return 0;}

     这个程序没有检错功能

    输入只能包含0-9,+,-,*,/,(,),#;

    #只能出现在表达式尾部表示输入结束

    保证你的表达式语法正确

    下面是一些例子

    有疑惑或者更好的解决方法的朋友,可以联系我,大家一起探讨。qq:1546431565
  • 相关阅读:
    希尔排序(Shell Sorting)
    插入排序(Insertion Sorting)
    选择排序(Select Sorting)
    冒泡排序(Bubble Sorting)
    排序算法(Sort Algorithm)
    递归(Recursion)
    包的导入
    Base64编码
    python各种模块,迭代器,生成器
    CF821 B. Okabe and Banana Trees 简单数学
  • 原文地址:https://www.cnblogs.com/mr-stn/p/9017273.html
Copyright © 2011-2022 走看看