我如何将用户选择的操作员加和分配给可变的操作员



我是C#的新手,但是我可以在LUA中进行编码,并且我试图在必要时使用我的一些技能选择获得结果。

我已经尝试搜索Google寻求解决方案,并且我尝试以不同的方式将其打印出来,但我无法弄清楚该怎么做。

using System;
namespace FirstConsoleProject
{
    class Program
    { 
        static void Main(string[] args) //This is a Method, named "Main". It's called when the program starts
        {
            int numberOne;
            int numberTwo;
            string method;
            Console.WriteLine("What would you like to do? <+, -, *, />");
            method = Console.ReadLine();
            Console.Write("Please type the first number: ");
            numberOne = Convert.ToInt32(Console.ReadLine());
            Console.Write("Please type the second number: ");
            numberTwo = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(numberOne + method + numberTwo + " = " + numberOne + method + numberTwo);
            Console.ReadKey();
        }
    }
}

我希望出现" numberOne numbertwo =答案",而不是" numberOne numberOne = numberOne numbertwo"。

您需要某种表达引擎来执行此操作。这可能像开关语句一样简单,就像您只有4位操作员,包括逃亡之类的东西。

以前的情况很容易编码:

class Program
{ 
    static void Main(string[] args) //This is a Method, named "Main". It's called when the program starts
    {
        double numberOne;
        double numberTwo;
        string method;
        Console.WriteLine("What would you like to do? <+, -, *, />");
        method = Console.ReadLine();
        Console.Write("Please type the first number: ");
        numberOne = Convert.ToDouble(Console.ReadLine());
        Console.Write("Please type the second number: ");
        numberTwo = Convert.ToDouble(Console.ReadLine());
        Console.WriteLine(numberOne + method + numberTwo + " = " + Calculate(numberOne,numberTwo,method));
        Console.ReadKey();
    }
    static double Calculate(double input1, double input2, string operator)
    {
        switch(operator)
        {
            case "+": return input1 + input2;
            case "-": return input1 - input2;
            case "*": return input1 * input2;
            case "/": return input1 / input2;
            default: throw new InvalidOperatorinException($"Unknown operator: {operator}");
        }
    }
}

最新更新