アプリ版:「スタンプのみでお礼する」機能のリリースについて

課題内容:
1.テキストファイルから数式(prefix形式)を読み取り、それを通常の数式(infix形式)に直してコンソールに出力。
2.数式内の変数xに代入する値をユーザーに求め、代入後の式の値を出力。
3.数式の微分(derivative)を求め出力。
4.2で入力された値を3の式のxと置き換え、置き換えた後の値を出力。

例としては下のようになります。
------------------------------------------------------------------
Enter file that contains the mathematical expression: formula1.txt
3*x
Enter a value for x: 4
(3*4) = 12
Derivative:((3*1) + (0*x))
Replacing x with 4 in derivative: ((3*1) + (0*4)) = 3
------------------------------------------------------------------
インプットファイル:formula1.txt
*
3
x

以下のクラスを使って問題を解かなければなりません。
・Formula.h and Formula.cpp
・Add.h and Add.cpp
・Multiply.h and Multiply.cpp
・Subtract.h and Subtract.cpp
・Divide.h and Divide.cpp
・Exponent.h and Exponent.cpp
・Constant.h and Constant.cpp
・Variable.h and Variable.cpp
(Formulaクラス以外の7つのクラスはFormulaクラスを継承し、Formulaクラスは下記の4つの仮想関数をもつものとします。)
・virtual void print()
・virtual void print(int)
・virtual void derivative()
・virtual int evaluate(int)
(他の7つのクラスはそれぞれコンストラクタ、デストラクタ、print()、derivative()、evaluate()を持ちます。 )


一応今までに書いたコードを載せておきます。恥ずかしながらinfix形式に直して出力するところまでしかできていません。どうぞどなたかお力添えをお願いたします。

#include <deque>
int main()
{
ifstream inFile;
inFile.open("input2.txt");
deque<char> oprt;
deque<char> other;
if (!inFile.is_open()) {throw "Failed opening file.";}
else
{
while (!inFile.eof())
{
char in;
inFile>>in;
if (in == '+' || in == '-' ||in == '*' || in == '/' || in == '^') oprt.push_front(in);
else other.push_back(in);
}
other.pop_back();
}

deque<char>::iterator it1 = oprt.begin();
deque<char>::iterator it2 = other.begin();
while (1)
{
if (it1 == oprt.end() && it2 == other.end()) break;
else
{
if (it2 != other.end()) {cout<<*it2<<" "; it2++;}
if (it1 != oprt.end()) {cout<<*it1<<" "; it1++;}
}
}

inFile.close();
return 0;

A 回答 (3件)

読み込みは


while (!inFile.eof())
{
  char in = 0;
  inFile>>in;
  if ( in != 0 ) {
    if (in == '+' || in == '-' ||in == '*' || in == '/' || in == '^') oprt.push_front(in);
    else other.push_back(in);
  }
}
// other.pop_back();
とすれば pop_backは不要 ... 読み込み失敗時のpush_backをしないようにする

表示部は otherが無くなるまでループすればいいので
for( ; it2 != other.end(); it2++ ) {
  cout << *it2;
  if ( it1 != oprt.end() ) {
    cout << *it1;
    it1++;
  }
}
といった具合では ...
    • good
    • 0
この回答へのお礼

回答どうもありがとうございます。
試してみます。

お礼日時:2009/05/07 00:53

コンストラクタの仕様がわからんとか「derivative の返り値が void なのはなんか変」とかは思うんだけど, それはともかく読み込みは再帰的にやるのが簡単だと思う.


1. 1文字読み込んでみて
2. 演算子ならそのあとに 2つの被演算子があるはずなのでそれらを再帰的に読み込む
3. 演算子でなければ変数か定数なので適切なオブジェクトを作る
という構造で OK のはず.
    • good
    • 0
この回答へのお礼

なるほど。。再帰をつかうと簡単なのですね。試してみます。
どうもありがとうございました。

お礼日時:2009/05/07 00:54

ついでだけど, 読み込んだ結果は Formula * にするだろうから, 「入力ストリームから読み込んで Formula * を返す」関数を作っておくべきでしょう.


再帰的に読み込むなら必須だし, そうでなくても「プログラムを読みやすくする」意味で関数にしておくべし.
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!