Advertisement
jokerbg

Enigmanation

Jan 24th, 2015
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.75 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. class Enigmanation
  4. {
  5.     static double CalcBrackets(string expr)
  6.     {
  7.         char[] expression = expr.ToCharArray();
  8.         double result = expression[0] - '0';
  9.  
  10.         for (int i = 2; i < expression.Length; i += 2)
  11.         {
  12.             if (expression[i - 1] == '+') result += (expression[i] - '0');
  13.             else if (expression[i - 1] == '-') result -= (expression[i] - '0');
  14.             else if (expression[i - 1] == '%') result %= (expression[i] - '0');
  15.             else if (expression[i - 1] == '*') result *= (expression[i] - '0');
  16.         }
  17.         return result;
  18.     }
  19.     static void Main()
  20.     {
  21.         string entry = Console.ReadLine();
  22.         char[] input = entry.ToCharArray();
  23.         List<string> list = new List<string>();
  24.  
  25.         double result = 0;
  26.         for (int i = 0; i < input.Length; i++)
  27.         {
  28.             if (input[i] == '(')
  29.             {
  30.                 int endInBracketIndex = entry.IndexOf(')', i);
  31.                 string insideBrackets = entry.Substring(i + 1, endInBracketIndex - i - 1);
  32.                 list.Add(CalcBrackets(insideBrackets).ToString());
  33.                 i = endInBracketIndex;
  34.             }
  35.             if (input[i] == ')') i += 1;
  36.             list.Add(input[i].ToString());
  37.         }
  38.  
  39.         result = double.Parse(list[0]);
  40.         for (int i = 2; i < list.Count; i++)
  41.         {
  42.             if (list[i - 1] == "+") result += double.Parse(list[i]);
  43.             else if (list[i - 1] == "-") result -= double.Parse(list[i]);
  44.             else if (list[i - 1] == "%") result %= double.Parse(list[i]);
  45.             else if (list[i - 1] == "*") result *= double.Parse(list[i]);
  46.         }
  47.         Console.WriteLine("{0:f3}", result);
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement