[栈/STL] 简易计算器
最近刚刚自学了一点点数据结构和STL,刚好写个简易的计算器 O(∩_∩)O
首先了解了一下逆波兰表达式
《大话数据结构》一书中阐释得较为易懂
1 #include<iostream> 2 #include<ctype.h>//isdigit() 3 #include <cstring> 4 #include<stack> 5 using namespace std; 6 7 stack<char> opCh; 8 stack<long long> opNum; 9 inline long long Calculate() 10 { 11 long long b = opNum.top(); 12 opNum.pop(); 13 long long a = opNum.top(); 14 opNum.pop(); 15 char operate = opCh.top(); 16 opCh.pop(); 17 18 switch (operate) 19 { 20 case '+': 21 return a + b; 22 case '-': 23 return a - b; 24 case '*': 25 return a * b; 26 case '/': 27 return a / b; 28 } 29 } 30 inline long long Ojrank(char ch) 31 { 32 switch (ch) 33 { 34 case '(': 35 return 0; 36 case '+': 37 case '-': 38 return 1; 39 case '*': 40 case '/': 41 return 2; 42 case ')': 43 return 3; 44 } 45 } 46 int main() 47 { 48 cout << "计算器1.0[仅支持整数的简单运算]" << endl; 49 cout << "请输入计算表达式:" << endl; 50 string expression; 51 cin >> expression; 52 int len = expression.length(); 53 54 long long topChRank, currentChRank; 55 long long i = 0; 56 long long number; 57 while (expression[i] != '=' && expression[i] != '\0') 58 { 59 if (isdigit(expression[i]))//数字 60 { 61 number = 0; 62 while (expression[i] != '=' && expression[i] != '\0' && isdigit(expression[i])) 63 { 64 number = number * 10 + (expression[i]-'0'); 65 i++; 66 } 67 opNum.push(number); 68 } 69 else//字符 70 { 71 if (opCh.empty()) {//字符栈为空 72 opCh.push(expression[i]); 73 i++; 74 continue; 75 } 76 topChRank = Ojrank(opCh.top());//获取优先级 77 currentChRank = Ojrank(expression[i]); 78 if (currentChRank == 0) {//左括号 79 opCh.push(expression[i]); 80 i++; 81 } 82 else if (currentChRank == 3) {//右括号 83 while (opCh.top() != '(') { 84 number = Calculate(); 85 opNum.push(number); 86 } 87 opCh.pop();//弹出左括号 88 i++; 89 } 90 else { 91 while (!opCh.empty() && currentChRank <= topChRank)//优先级低的不能压在高的上面 92 { 93 number = Calculate(); 94 opNum.push(number);; 95 topChRank = Ojrank(expression[i]);//即时更新栈顶字符优先级 96 } 97 opCh.push(expression[i]); 98 i++; 99 } 100 } 101 } 102 103 while (!opCh.empty()) 104 { 105 number = Calculate(); 106 opNum.push(number); 107 } 108 if(expression[len-1] == '=') 109 cout << expression << number << endl; 110 else 111 cout << expression <<'='<< number << endl; 112 return 0; 113 }
本文来自博客园,作者:泥烟,CSDN同名, 转载请注明原文链接:https://www.cnblogs.com/Knight02/p/14599587.html