You can try some metaprogramming as shown below. It has the advantage that C itself evaluates the expressions, rather than trying to make its own evaluator (and possibly wrong):
#include <stdlib.h> #include <iostream> #include <fstream> using namespace std; int main (void) { int n1, n2, n3; const char *ops[] = {" + ", " - ", " * ", " / ", " % ", 0}; const char **op1, **op2; ofstream of; of.open ("prog2.cpp", ios::out); of << "#include <iostream>\n"; of << "using namespace std;\n"; of << "#define IXCOUNT 49\n\n"; of << "static int mkIdx (int tot) {\n"; of << " int ix = (IXCOUNT / 2) + tot;\n"; of << " if ((ix >= 0) && (ix < IXCOUNT)) return ix;\n"; of << " cout << \"Need more index space, " << "try \" << IXCOUNT + 1 + (ix - IXCOUNT) * 2 << \"\\n\";\n"; of << " return -1;\n"; of << "}\n\n"; of << "int main (void) {\n"; of << " int tot, ix, used[IXCOUNT];\n\n"; of << " for (ix = 0; ix < sizeof(used)/sizeof(*used); ix++)\n"; of << " used[ix] = 0;\n\n";
for (n1 = 2; n1 <= 4; n1++) { for (n2 = 2; n2 <= 4; n2++) { if (n2 != n1) { for (n3 = 2; n3 <= 4; n3++) { if ((n3 != n1) && (n3 != n2)) { for (op1 = ops; *op1 != 0; op1++) { for (op2 = ops; *op2 != 0; op2++) { of << " tot = " << n1 << *op1 << n2 << *op2 << n3 << ";\n"; of << " if ((ix = mkIdx (tot)) < 0) return ix;\n"; of << " if (!used[ix])\n"; of << " cout << " << n1 << " << \"" << *op1 << "\" << " << n2 << " << \"" << *op2 << "\" << " << n3 << " << \" = \" << tot << \"\\n\";\n"; of << " used[ix] = 1;\n\n"; } } } } } } } of << " return 0;\n"; of << "}\n"; of.close(); system ("g++ -o prog2 prog2.cpp ; ./prog2"); return 0; }
This gives you:
2 + 3 + 4 = 9 2 + 3 - 4 = 1 2 + 3 * 4 = 14 2 + 3 / 4 = 2 2 + 3 % 4 = 5 2 - 3 + 4 = 3 2 - 3 - 4 = -5 2 - 3 * 4 = -10 2 - 3 % 4 = -1 2 * 3 + 4 = 10 2 * 3 * 4 = 24 2 / 3 + 4 = 4 2 / 3 - 4 = -4 2 / 3 * 4 = 0 2 % 3 + 4 = 6 2 % 3 - 4 = -2 2 % 3 * 4 = 8 2 * 4 + 3 = 11 2 / 4 - 3 = -3
I am not quite sure of the wisdom to convey this as an appointment, however :-)
source share