Итак, если бы я собирался написать это, я бы начал с перечислимого типа для операций:
public enum ArithmeticOperation
{
Add,
Subtract,
Multiply,
Divide,
}
Я бы написал небольшую вспомогательную функцию:
private static string ShowEnumOptions<T>() where T : struct
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException($"Type: {typeof(T).ToString()} must be an enumerated type");
}
var options = Enum.GetNames(typeof(T));
return string.Join("/", options);
}
(новейшая версия C # (которую я пока не использую) допускает ограничение System.Enum для параметра универсального типа, что упростит это)
Тогда я бы написал свою основную программу, чтобы она выглядела так:
static void Main(string[] args)
{
while (true)
{
ArithmeticOperation operation = default(ArithmeticOperation);
var goodOperation = false;
while (!goodOperation)
{
Console.Write(
$"Enter operation (one of [{ShowEnumOptions<ArithmeticOperation>()}] or \"Quit\"): ");
var response = Console.ReadLine();
if (string.Equals(response, "Quit", StringComparison.InvariantCultureIgnoreCase))
{
return; //quit the app
}
if (Enum.TryParse<ArithmeticOperation>(response, true, out operation))
{
goodOperation = true;
}
}
double value1 = 0.0;
double value2 = 0.0; //initialize them to keep the compiler happy
var goodDouble = false;
while (!goodDouble)
{
Console.Write("Enter the first number: ");
var response = Console.ReadLine();
if (double.TryParse(response, out value1))
{
goodDouble = true;
}
}
goodDouble = false;
while (!goodDouble)
{
Console.Write("Enter the second number: ");
var response = Console.ReadLine();
if (double.TryParse(response, out value2))
{
goodDouble = true;
}
}
//ok, got an operation and two numbers
double result = 0.0;
switch (operation)
{
case ArithmeticOperation.Add:
result = value1 + value2;
break;
case ArithmeticOperation.Subtract:
result = value1 - value2;
break;
case ArithmeticOperation.Multiply:
result = value1 * value2;
break;
case ArithmeticOperation.Divide:
if (value2 == 0.0)
{
Console.WriteLine("Division by zero is invalid");
result = double.NaN; //NaN means "not a number"
break;
}
result = value1 / value2;
break;
}
Console.WriteLine($"Result is {result}");
}
}
Обратите внимание, что я проверяю все входные данные на достоверность. Всегда предполагайте, что ваши пользователи будут вводить неверные данные. Также обратите внимание, что я проверяю свой дубль на равенство с нулем. Проверка на равенство с плавающей запятой, как правило, плохая идея, но это правильная вещь.
Тогда, как псевдокод, все, что я напишу, будет:
// Get the operation (one of add/subtract/multiply or divide) - or allow the user to quit
// Get each of value1 and value2 as doubles
// Based on the operation, calculate the result (pay attention to division by zero)
// Show the result
// Loop back and let the user try again (or quit)