2009-07-24 2 views
0

char 값을 읽는 중 문제가 있습니다. 아래 프로그램을 참조하십시오. 중위 표현을 평가하고 싶습니다.
'10', '*', '20'을 읽고 사용하고 싶습니다. 그러나 문자열 인덱서를 사용할 경우 [0]은 '1'이되고 '10'이 아니므로 기대 한 결과를 얻을 수 없습니다. 너희들은 나에게 뭔가 제안 할 수 있니? 운동을 의미 정확히 방법 당신이 문자열을 분할 할 - 코드는 문자열을 분할해야합니다인덱서를 사용하여 문자열에서 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

는 C#에서입니다. 나는 당신이 패턴을 다루고 있기 때문에 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

관련 문제