四則演算
勢いに任せて、C++版を実装。
#include <iostream> #include <string> using namespace std; int calc(string expr, int x) { bool flgInit = true; // 初期処理フラグ int ret; // 戻り値 int sIdx = 0; // 文字の切り出し開始位置 int eIdx = 0; // 文字の切り出し終了位置 string calcPtn; // 演算子文字列 string tmpStr; int tmpInt; while(eIdx != -1) { eIdx = expr.find(" ", sIdx); if(eIdx == -1) { tmpStr = expr.substr(sIdx); // 最後の文字 } else { tmpStr = expr.substr(sIdx, eIdx - sIdx); } if(tmpStr.compare("x") == 0) { tmpInt = x; // 変数 } else { tmpInt = atoi(tmpStr.c_str()); } if(tmpInt == 0) { calcPtn = tmpStr; // 演算子 } else { if(flgInit) { ret = tmpInt; // 初期処理 flgInit = false; } else { if(calcPtn.compare("+") == 0) { ret += tmpInt; } else if(calcPtn.compare("-") == 0) { ret -= tmpInt; } else if(calcPtn.compare("*") == 0) { ret *= tmpInt; } else if(calcPtn.compare("/") == 0) { ret /= tmpInt; } } } sIdx = eIdx + 1; } return ret; } void main() { for(int x = 1; x < 10; x++) { cout << calc("x + x * x - x / 2", x) << endl; } }
atoi()が数値以外だと0を返すので、
変数や定数に0を入れると、うまく動きませんが…(´Д`;