{{ message }}

Instantly share code, notes, and snippets.

# wilfreddesert/Calculator.cs

Created May 20, 2018
A simple calculator.
 using System; namespace CalculatorDelegate { class Program { private static double Item1 { get; set; } private static double Item2 { get; set; } private static string Action { get; set; } private delegate double Del(double a, double b); private static void Main(string[] args) { while (true) { Console.WriteLine(ParseInput()); } } private static double ParseInput() { Console.WriteLine("Enter a mathematical expression, please"); var userInput = Console.ReadLine(); var userInputLength = userInput.Length; Del handler; for (var i = 1; i < userInputLength; i++) { if ( userInput[i].Equals('+') || userInput[i].Equals('-') || userInput[i].Equals('*') | userInput[i].Equals('/')) { Action = Convert.ToString(userInput[i]); double.TryParse(userInput.Substring(0, i), out var tempItem1); double.TryParse(userInput.Substring(i + 1, userInputLength - i - 1), out var tempItem2); Item1 = tempItem1; Item2 = tempItem2; if (Action.Equals("/") && Item2 == 0) { Console.WriteLine("You can't divide by zero"); return 0; } break; } } switch (Action) { case "+": handler = GetSum; break; case "-": handler = GetDiff; break; case "*": handler = GetMult; break; case "/": handler = GetDiv; break; default: return 0; } return handler(Item1, Item2); } private static double GetSum(double a, double b) { return a + b; } private static double GetDiff(double a, double b) { return a - b; } private static double GetMult(double a, double b) { return a * b; } private static double GetDiv(double a, double b) { return a / b; } } }