我需要帮助简化这个程序

本文关键字:程序 帮助 | 更新日期: 2023-09-27 18:13:12

        decimal sum;
        int index;
        Console.WriteLine("Enter numbers you want to calculate:");
        string Expression = Console.ReadLine();
        if (Expression.Contains("+"))
        {
            index = Expression.IndexOf("+");
            int secondnumber = index + 1;
            decimal a = decimal.Parse(Expression.Substring(0, index));
            decimal b = decimal.Parse(Expression.Substring(secondnumber));
            sum = a + b;
            Console.WriteLine("{0}={1}", Expression, sum.ToString("0.###"));
        } else if (Expression.Contains("-"))
        {
            index = Expression.IndexOf("-");
            int secondnumber = index + 1;
            decimal a = decimal.Parse(Expression.Substring(0, index));
            decimal b = decimal.Parse(Expression.Substring(secondnumber));
            sum = a - b;
            Console.WriteLine("{0}={1}", Expression, sum.ToString("0.###"));
        } else if (Expression.Contains("/"))
        {
            index = Expression.IndexOf("/");
            int secondnumber = index + 1;
            decimal a = decimal.Parse(Expression.Substring(0, index));
            decimal b = decimal.Parse(Expression.Substring(secondnumber));
            sum = a / b;
            Console.WriteLine("{0}={1}", Expression, sum.ToString("0.###"));
        } else if (Expression.Contains("*"))
        {
            index = Expression.IndexOf("*");
            int secondnumber = index + 1;
            decimal a = decimal.Parse(Expression.Substring(0, index));
            decimal b = decimal.Parse(Expression.Substring(secondnumber));
            sum = a * b;
            Console.WriteLine("{0}={1}", Expression, sum.ToString("0.###"));
        } else
        {
            Console.WriteLine("ERROR");
        }

问题是我不能简化代码而不弄乱它并抛出异常。任何帮助都会很感激。我还需要帮助。indexof方法是否有在选择之外做它?我试过了,但是它总是乱糟糟的

我需要帮助简化这个程序

由于所有"if块"都遵循相同的模式:

  • 对1个字符的操作符进行分割
  • 解析操作符左边的小数点和右边的小数点
  • 对它们执行一个功能

可以将函数存储在Dictionary中:

var functionsByOperator = new Dictionary<char, Func<decimal, decimal, decimal>>();
functionsByOperator['+'] = (left, right) => left + right;
functionsByOperator['*'] = (left, right) => left * right;
// etc

然后剩下的代码变得不那么重复:

// the below array is required for the IndexOfAny method later on
char[] operators = new List<char>(functionsByOperator.Keys).ToArray();
Console.WriteLine("Enter numbers you want to calculate:");
string Expression = Console.ReadLine();
int index = Expression.IndexOfAny(operators);
if (index < 0)
{
    Console.WriteLine("ERROR");
    return;
}
decimal a = decimal.Parse(Expression.Substring(0, index));
decimal b = decimal.Parse(Expression.Substring(index + 1));
char oper = Expression[index];
decimal sum = functionsByOperator[oper](a, b);
Console.WriteLine("{0}={1}", Expression, sum.ToString("0.###"));