我需要知道如何得到一个带有变量的方程,并让它计算并输出该变量的值。方程式的例子。
2900 =1*T* ((52 + 6) / 12)
我需要程序获取所有的值,并给我'T‘的值。我们将非常感谢您的任何帮助:)
发布于 2012-11-25 12:26:01
首先将方程重新排列为T=...形式。
2900 = 1 * T * ((52 + 6) / 12)变成(例如)
T = 2900/(52 + 6) * 12 / 1接下来,将数字替换为变量
T = a/(b + c) * d / e然后编写一个函数来计算给定a-e的T
double T(double a, double b, double b, double c, double d, double e) {
 return  a/(b + c) * d / e;
}然后像这样使用它
double T = T(2900, 52, 6, 12, 1)发布于 2012-11-25 13:18:17
如果方程是相同的,只有参数改变-然后只需将其重新排列为变量。
如果整个等式是用户输入,那么它很快就会变得丑陋("2*cos(log(x^3)) =- e^tg(x)"),并且没有银弹。你能做的最简单的事情就是在运行时评估它(例如使用NCalc),并“强制”解决方案。
发布于 2012-11-25 14:33:59
下面是一个糟糕的解决方案,使用CSharpCodeProvider将等式编译为代码,然后使用简单的二进制搜索来搜索T值。
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Linq;
using System.Reflection;
namespace EquationSolver
{
    public class EquationSolver
    {
        MethodInfo meth;
        double ExpectedResult;
        public EquationSolver(string equation)
        {
        var codeProvider = new CSharpCodeProvider();            
        var splitted = equation.Split(new[] {'='});
        ExpectedResult = double.Parse(splitted[0]);
        var SourceString = "using System; namespace EquationSolver { public static class Eq { public static double Solve(double T) { return "+
            splitted[1] + ";}}}";
        System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
        parameters.GenerateInMemory = true;
        CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, SourceString);
        var cls = results.CompiledAssembly.GetType("EquationSolver.Eq");
        meth = cls.GetMethod("Solve", BindingFlags.Static | BindingFlags.Public);
    }
    public double Evaluate(double T)
    {            
        return (double)meth.Invoke(null, new[] { (object)T });
    }
    public double SearchT(double start, double end, double tolerance)
    {            
        do
        {
            var results = Enumerable.Range(0, 4).Select(x => start + (end - start) / 3 * x).Select(x => new Tuple<double, double>(
                x, Evaluate(x))).ToArray();
            foreach (var result in results)
            {
                if (Math.Abs(result.Item2 - ExpectedResult) <= tolerance)
                {
                    return result.Item1;
                }
            }
            if (Math.Abs(results[2].Item2 - ExpectedResult) > Math.Abs(results[1].Item2 - ExpectedResult))
            {
                end -= (end - start) / 3;                    
            }
            else
            {
                start += (end - start) / 3;
            }
        } while (true);
    }
  }
}就目前而言,它有严重的局限性:
必须首先说明预期的结果(在你的例子中是2900)。要解的等式必须在等号后面说明,只有一个变量,名为T。T本身可以存在于多个地方通过equation.
使用示例:
var eq = new EquationSolver( "2900 = 1 * T * ((52 + 6.0) / 12)");
var r = eq.SearchT(int.MinValue,int.MaxValue,0.001);https://stackoverflow.com/questions/13548179
复制相似问题