Created
May 20, 2018 12:50
-
-
Save wilfreddesert/dc188a23b8028b8516877a7349e59066 to your computer and use it in GitHub Desktop.
A simple calculator.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment