[英]how to get the Operator type from the string(a + b) Input in c#?
For example If the user gives input as a + b, process should be done as adding two variables that has been already declared as int a, int b 例如,如果用户将输入作为a + b进行输入,则应添加两个已经声明为int a,int b的变量来完成该过程
int a = 7;
int b = 8;
string formula = console.readline();
this is where I need Help if the user types a + b as formula we should addition on that a and b, User can use any binary operator, formula should get that operator from user input, Please help 这是我需要帮助的地方,如果用户键入a + b作为公式,我们应该在该值上加上a和b,用户可以使用任何二进制运算符,公式应从用户输入中获取该运算符,请提供帮助
You try to evaluate the math expression. 您尝试评估数学表达式。 I suggest to use NCalc 我建议使用NCalc
NCalc is a mathematical expressions evaluator in .NET. NCalc是.NET中的数学表达式评估器。 NCalc can parse any expression and evaluate the result, including static or dynamic parameters and custom functions. NCalc可以解析任何表达式并评估结果,包括静态或动态参数以及自定义函数。
You could do like this: 您可以这样:
int a = 7;
int b = 8;
string formula = "a+b";
formula=formula.Replace("a",a.ToString()).Replace("b",b.ToString());
var calc = new System.Data.DataTable();
Console.WriteLine(calc.Compute(formula, ""));
Made this a while ago to evaluate expressions like this 前一阵子来评估这样的表达式
private static double Calc(string expression)
{
try
{
var table = new System.Data.DataTable();
table.Columns.Add("expression", string.Empty.GetType(), expression);
System.Data.DataRow row = table.NewRow();
table.Rows.Add(row);
return double.Parse((string)row["expression"]);
}
catch (Exception)
{
return 0;
}
}
This code allows the user to enter two numbers and the operator he or she wants 此代码允许用户输入两个数字,并输入他或她想要的运算符
Console.WriteLine("Please enter the first number");
int a = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the operator you want to use");
string c = Console.ReadLine() ;
Console.WriteLine("Enter the last number");
int b = int.Parse(Console.ReadLine());
string formula = "acb";
formula = formula.Replace("a", a.ToString()).Replace("b", b.ToString()).Replace("c", c.ToString());
var calc = new System.Data.DataTable();
Console.WriteLine(calc.Compute(formula, ""));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.