24点游戏 程序(二)

前面既然确定了后缀表达式的序列。

那就可以开始遍历了。

#include #include #include #include #include #include using namespace std; struct TOperData { int operType; double data; }; //检查计算的参数是否合法,也可以用于过滤一些重复的表达式 bool checkjisuan(double a, double b, int op) { //处理除以0的情况 if (op == '/' && b < 1e-6 && b > -1e-6) return false; return true; } //求值 double jisuan(double a, double b, int op) { switch(op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; default: return -1; } } //计算表达式的值 double process(TOperData data[]) { int len = 7; stack suffix; for (int i = 0; i < len; i++) { if (data[i].operType == 0) { suffix.push(data[i]); } else if (data[i].operType > 0) { if (suffix.empty()) return false; if (suffix.top().operType == 0) { double a = suffix.top().data; suffix.pop(); if (!suffix.empty() && suffix.top().operType == 0) { double b = suffix.top().data; suffix.pop(); if (!checkjisuan(b,a,data[i].operType)) return -1; double c = jisuan(b,a,data[i].operType); TOperData opdata; opdata.operType = 0; opdata.data = c; suffix.push(opdata); } else { return -1; } } else { return -1; } } } if (suffix.empty()) return -1; if (suffix.top().operType == 0) { double r = suffix.top().data; suffix.pop(); if (suffix.empty()) return r; } return -1; } //打印成功的结果 void printResult(TOperData computeData[]) { for (int i = 0; i < 7; i++) { if (computeData[i].operType == 0) { cout< -1e-6 && r-24 < 1e-6) { cout< 这样执行得到50000个结果,耗时30s左右


仔细看这些结果,可以发现有一些重复的。

接下来要简单消除一下重复,以及为了结果更直观,把后缀表达式改成中缀表达式。

转载于:https://www.cnblogs.com/marryZhan/archive/2012/02/26/2497559.html

你可能感兴趣的:(24点游戏 程序(二))