2009-07-24 13 views
0

char値の読み取りに問題があります。 以下のプログラムを参照してください。中置式を評価したい
「10」、「*」、「20」を読み込んで使用したいのですが、文字列インデクサーs [0]が '1'で '10'私は期待される結果を得ることができません。 あなたは私に何かを提案できますか?あなたは文字列を分割する方法を正確をワークアウトを意味します - コードは、文字列を分割する必要がありますC#でインデクサーを使用して文字列から2文字を取得する際の問題

class Program 
    { 
     static void Main(string[] args) 
     { 
      string infix = "10*2+20-20+3"; 
      float result = EvaluateInfix(infix); 
      Console.WriteLine(result); 
      Console.ReadKey(); 

     } 

     public static float EvaluateInfix(string s) 
     { 
      Stack<float> operand = new Stack<float>(); 
      Stack<char> operator1 = new Stack<char>(); 
      int len = s.Length; 
      for (int i = 0; i < len; i++) 
      { 
       if (isOperator(s[i])) // I am having an issue here as s[i] gives each character and I want the number 10 
        operator1.Push(s[i]); 
       else 
       { 
        operand.Push(s[i]); 
        if (operand.Count == 2) 
         Compute(operand, operator1); 
       } 
      } 

      return operand.Pop(); 


     } 

     public static void Compute(Stack<float> operand, Stack<char> operator1) 
     { 
      float operand1 = operand.Pop(); 
      float operand2 = operand.Pop(); 
      char op = operator1.Pop(); 

      if (op == '+') 
       operand.Push(operand1 + operand2); 
      else 
       if(op=='-') 
        operand.Push(operand1 - operand2); 
       else 
        if(op=='*') 
         operand.Push(operand1 * operand2); 
        else 
         if(op=='/') 
          operand.Push(operand1/operand2); 
     } 




     public static bool isOperator(char c) 
     { 
      bool result = false; 
      if (c == '+' || c == '-' || c == '*' || c == '/') 
       result = true; 
      return result; 
     } 




    } 
} 
+0

を否決、私はyがこの質問だった理解していませんか? – Learner

+0

私はここで似たようなことをしました:ページの一番下にあるwww.twipler.com/experimentソースコードリンク。 –

答えて

0

です。あなたがパターンを扱っているので、Regex.Splitがこの場合に最も適切な分割ツールであると思われます。また、独自の分割ルーチンを記述することもできます。

整数と演算子のみを扱う必要がありますか?空白はどうですか?角かっこ?先行する負の数?負の数による乗算(「3 * -5」など)?

+0

yaa ..最初に基本コードを書いておきたいと思いますが、あなたが言及したケースのために拡張します – Learner

0

ストア変数内の数値、そしてあなたがオペレータまたは文字列の末尾に遭遇すると、その押し:​​

int num = 0; 
foreach (char c in s) { 
    if (isOperator(c)) { 
     if (num != 0) { 
     operand.Push(num); 
     num = 0; 
     } 
     operator1.Push(c); 
     if (operand.Count == 2) { 
     Compute(operand, operator1); 
     } 
    } else { 
     num = num * 10 + (int)(c - '0'); 
    } 
} 
if (num != 0) { 
    operand.Push(num); 
} 
+0

@Guffa:最後のオペランドのために...あなたはforeachの後にifを追加しました。したがって評価されません 5 + 10 + 5 + 16 ... したがって、16は評価されません。 – Learner

+0

@Learner:計算の仕方にはあまり集中しませんでした。最後のif文の中にComputeのチェックを追加するだけです。 – Guffa

関連する問題