0

我有一个包含 5 个数字的十进制类型列表:{10, 9, 100,73,3457}. 我在这些数字之间有另一个字符串类型的 4 个运算符的列表:*乘法-减法/除法+加法。

我怎样才能得到字符串的结果?我不知道如何强加运算符优先级。

10 * 9 - 100 / 73 + 3457 = ???

这是我的代码,我以完全错误的方式解决问题,应该怎么做?

static List<decimal> numbers = new List<decimal>();
static List<string> operators = new List<string>();

foreach (decimal number in numbers)
{
    foreach (string operatorz in operators)
    {
        resultnumber = 
    }
}
4

3 回答 3

4

希望我有你想要的,这将使所有数字交叉连接到他们自己,然后进入运营商。您已经列出了二元运算符,所以我想每个运算符都需要两个操作数。结果行数为 =numbers.Length * numbers.Length * operators.Length

void Main()
{
   var numbers = new[] { 10, 9, 100, 73, 3457 };
   var operators = new [] { "*", "+", "/", "-" };


    var r = from n1 in numbers
            from n2 in numbers
            from op in operators
            select string.Format("{0} {1} {2} = {3}",
                                  n1, op, n2,   Perform(n1, op, n2));

}

public int Perform(int val1, string @operator, int val2)
{
    //main core if your question, consider to extract operators to outer level
    var operators = new Dictionary<string, Func<int, int, int>>
    {
        {"+", (v1, v2) => v1 + v2},
        {"/", (v1, v2) => v1 / v2},
        {"*", (v1, v2) => v1 * v2},
        {"-", (v1, v2) => v1 - v2},
    };

    return operators[@operator](val1, val2);
}

结果是

10 * 10 = 100 
10 + 10 = 20 
10 / 10 = 1 
10 - 10 = 0 
10 * 9 = 90 
....
于 2013-03-22T13:16:45.150 回答
1

不完全清楚你想要什么。但是假设这些运算符位于数字之间,并解析为本地运算符优先级:简单的方法是编写脚本。您的运算符优先级将是本地的。

脚本

private static void Main(string[] args)
{
    var numbers = new[]{ 10, 9, 100, 73, 3457 };
    var ops = new[] { "*","-","/","+" };

    if (numbers.Length != ops.Length + 1)
        throw new Exception("TODO");

    string statement = numbers[0].ToString();

    for (int i = 0; i < ops.Length; i++)
    {
        statement += string.Format(" {0} {1}", ops[i], numbers[i + 1]);
    }

    Console.WriteLine("Statement: " + statement);

    var method = String.Format(@"int Product() {{ return {0}; }} ", statement);

    Console.WriteLine("Method: " + method);


    var Product = CSScript.Evaluator.CreateDelegate(method);
    int result = (int)Product();

    Console.WriteLine(result);
}

结果:

Statement: 10 * 9 - 100 / 73 + 3457
Method: int Product() { return 10 * 9 - 100 / 73 + 3457; }
3546
Press any key to continue . . .
于 2013-03-22T13:25:57.720 回答
-1

http://msdn.microsoft.com/fr-fr/library/s53ehcz3(v=VS.80).aspx

您可以使用自己的类来处理计算

于 2013-03-22T13:17:30.887 回答