计算公式方程

时间:2015-05-29 14:48:21

标签: c# visual-studio-2010

当前代码接受公式并执行计算。我找到了第一个操作员的位置,并在左右两侧计算出数字 -

 //array of characters
            char[] arrayOfOperators = {'/', '*', '+', '/'};
            string input = "5+4+6+1";

               foreach (int i in input)  
               {

                while (arrayOfOperators.Any(input.Contains))
               {


                 int sign = input.IndexOf(  ); //current operator ()
                 Console.WriteLine(sign);

                 string beforeOperator = input.Substring(0, sign);
                 string afterOperator = input.Substring(sign + 1); 

                 // populate these two variables
                 int previousOperatorPosition = (beforeOperator.LastIndexOf('+'));   //   instead of +??      
                 int nextOperatorPosition = (afterOperator.IndexOf('+'));     //   instead of +??  

                 //parse and store in a variable
                 int leftNumber = int.Parse(beforeOperator.Substring(previousOperatorPosition + 1));
                 int rightNumber = 0;

                 if (nextOperatorPosition != -1) 
                 {
                   rightNumber = int.Parse(afterOperator.Substring(0, nextOperatorPosition));    
                 }
                 else
                 {
                    rightNumber = int.Parse(afterOperator);
                 }          
                 // Do calculation with 2 previous variables, and store result in variable
                 int result = (leftNumber + rightNumber);
                 input = (beforeOperator.Substring(0, previousOperatorPosition + 1) + result +  (afterOperator.Substring(1)));

我正在尝试获取当前的运算符 - int sign = input.IndexOf( );我不确定括号中应该包含什么

以及 -

int previousOperatorPosition = (beforeOperator.LastIndexOf('+'));   //   instead of +??      
int nextOperatorPosition = (afterOperator.IndexOf('+'));     //   instead of +??  

非常感谢任何帮助,谢谢

0 个答案:

没有答案