hch
2025-09-03 f27e132391f11de7a199d27a32c142f41d002295
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using Jace;
using System;
using System.Collections.Generic;
 
public static class JaceCalculator
{
    private static readonly CalculationEngine Engine = new CalculationEngine();
 
    /// <summary>
    /// 解析并计算数学表达式
    /// </summary>
    /// <param name="formula">数学表达式字符串</param>
    /// <param name="variables">变量字典</param>
    /// <returns>计算结果</returns>
    public static double Calculate(string formula, Dictionary<string, double> variables)
    {
        if (string.IsNullOrEmpty(formula))
        {
            throw new ArgumentException("Formula cannot be null or empty.");
        }
 
        if (variables == null || variables.Count == 0)
        {
            throw new ArgumentException("Variables dictionary cannot be null or empty.");
        }
 
        try
        {
            return Engine.Calculate(formula, variables);
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"Failed to calculate formula: {ex.Message}", ex);
        }
    }
 
    public static void Init()
    { 
        Engine.AddFunction("int", (Func<double, double>)(x => (int)x));
    }
}