Our entire programme is now downLastly, as for a bonus to 26 lines with appropriate whitespacethis answer, and supports much more than your original didyou can also add alias operations. (Your original was 44 lines.What do I mean? Well what if I naturally use *
instead of x
for multiplication?)
This is super easy:
// Let's add our alias operations, */x
operations.Add("*", (x, y) => operations["x"](x, y));
Simply add them after the var operations
statement.
var operations = new Dictionary<string, Func<double, double, double>>
{
{"x", (x, y) => x * y },
{"/", (x, y) => x / y },
{"+", (x, y) => x + y },
{"-", (x, y) => x - y },
{"^", (x, y) => Math.Pow(x, y) },
{"%", (x, y) => x % y }
};
// Let's add our alias operations, */x
operations.Add("*", (x, y) => operations["x"](x, y));
Boom, now you can use *
instead of x
for multiplication. (But you can still use x
as well.)
Our entire programme is now down to 28 lines with appropriate whitespace, and supports much more than your original did. (Your original was 44 lines.)
var prompter = new ConsolePrompt(null);
Console.WriteLine("Hello, welcome to Alex's basic calculator!");
Console.ReadLine();
var operations = new Dictionary<string, Func<double, double, double>>
{
{"x", (x, y) => x * y },
{"/", (x, y) => x / y },
{"+", (x, y) => x + y },
{"-", (x, y) => x - y },
{"^", (x, y) => Math.Pow(x, y) },
{"%", (x, y) => x % y }
};
// Let's add our alias operations, */x
operations.Add("*", (x, y) => operations["x"](x, y));
do
{
var firstNum = prompter.Prompt<double>("Enter the first number in your basic equation", PromptOptions.Required);
var secondNum = prompter.Prompt<double>("Enter the second number in your basic equation", PromptOptions.Required);
var operation = prompter.Prompt<string>("Ok now enter your operation (" + string.Join(", ", operations.Keys) + ")", PromptOptions.Required, null, null, x => operations.Keys.Contains(x));
var answer = operations[operation](firstNum, secondNum);
Console.WriteLine($"{firstNum} {operation} {secondNum} = {answer}");
Console.ReadLine();
} while (prompter.Prompt("Enter exit to quit, anything else to continue", PromptOptions.Optional, "", parseResultMethod: x => x.ToLowerInvariant()) != "exit");