
注意:前两种方法只能算一位数的运算,第三种方法可以两位数以上的运算
这有两种方法,中心思想是一样的只不过定义的字符类型不一样
第一种方法用的是 字符指针类型 (我认为这种方法更好)
#include#include using namespace std; double cal(char* A) { stack s; char ch = *A; int res = 0; while (ch != '#') { if (ch >= '0' && ch <= '9') s.push(ch - '0'); else if(ch != ' ') { int num1 = s.top(); s.pop(); int num2 = s.top(); s.pop(); if (ch == '+') res = num1 + num2; else if (ch == '-') res = num2 - num1; else if (ch == '*') res = num1 * num2; else if (ch == '/') res = num1 / num2; s.push(res); } ch = *A++; } return s.top(); s.pop(); } int main() { char* A = (char*)"3 4 + 5 * 6 - #"; printf("%.2lf n", cal(A)); }
第二种用的是 字符数组类型
#include#include using namespace std; double cal(char ch[]) { stack s; int i = 0; int res = 0; while (ch[i] != ' ') { if (ch[i] >= '0' && ch[i] <= '9') s.push(ch[i] - '0'); else if(ch[i] != ' ') { int num1 = s.top(); s.pop(); int num2 = s.top(); s.pop(); if (ch[i] == '+') res = num1 + num2; else if (ch[i] == '-') res = num2 - num1; else if (ch[i] == '*') res = num1 * num2; else if (ch[i] == '/') res = num1 / num2; s.push(res); } i++; } return s.top(); s.pop(); } int main() { char A[999] = "3 4 + 5 * 6 -"; printf("%.2lf n", cal(A)); }
第三种方法会用到
① 使用stringstream类 和 getline方法 使得将字符串以空格划分(java里面直接用split函数不要太方便,C++只能自己写一个split函数,这里为了方便,使用getline方法)。 头文件#include
② 运用正则表达式,只要不是运算符(也就是是数字)我们就将他入栈。\d+表示从多位数,使用regex库里面的regex_match函数。
③ 运用atoi函数(整型)atof(浮点型)atol(长整型),将string转为double,atof()函数需要多少const char* 类型,但我们的是string类型,所以我们要多加个string.c_str()函数。
#include#include #include #include #include using namespace std; double cal(string a) { stringstream input(a); string str, ch; stack s; //用STL库里面的栈,这样方便 while (getline(input, str, ' ')) //三个参数分别是 输入流,字符串常引用,分割符 { ch = str; double res = 0; while (ch != " ") { if (regex_match(ch, regex("\d+")))//正则表达式,当传入字符串是多位数就入栈 { double a = atoi(ch.c_str()); s.push(a); } else { double num1 = s.top(); s.pop(); double num2 = s.top(); s.pop(); if (ch == "+") res = num1 + num2; else if (ch == "-") res = num2 - num1; else if (ch == "*") res = num1 * num2; else if (ch == "/") res = num1 / num2; s.push(res); } break; } } return s.top(); s.pop(); } int main() { string s = "300 4 + 5 * 6 -"; //多位数运算 printf("%.2lf n", cal(s)); }
如有错误请斧正,谢谢!!!