我有一根类似str = " 4+ 6 * 30";
的绳子。我必须使用C#对此执行算术操作;该问题的解决方案如下所示。
string temp = " 4 + 6 * 5";
int firstNaum = 0;
int secondNum = 0;
int ThirdNum = 0;
int finalResults = 0;
//Spliting strings
string[] withoutOperator = temp.Split('\t',' ','*' , '+');
//Iterating strings
int counter = 0;
foreach (var res in withoutOperator)
{
if (!string.IsNullOrEmpty(res) && counter ==1)
{
firstNaum = Convert.ToInt32(res);
}
if (!string.IsNullOrEmpty(res) && counter== 4)
{
secondNum = Convert.ToInt32(res);
}
if (!string.IsNullOrEmpty(res) && counter == 7)
{
ThirdNum = Convert.ToInt32(res);
}
counter += 1;
}
finalResults = firstNaum + secondNum * ThirdNum;
发布于 2014-07-24 21:46:06
计算数学表达式的最简单和最简单的方法之一是使用DataTable类的计算方法:
DataTable dt = new DataTable();
int answer = (int)dt.Compute("2+(4*3)*4", "");
答案是50。
请注意,您必须捕获异常以捕获无效表达式。
发布于 2014-07-24 16:23:53
你的解决方案非常有限。因为它只接受以下格式的字符串( x1 x2 x3
),并应用于函数x1+x2*x3
。
要构建表达式计算器,您需要完成以下步骤:
发布于 2014-07-24 15:21:03
你能澄清你想让我们回溯什么吗。
我的想法是:
Convert.ToInt32(res)
,而是使用int.TryParse(res, out n)
。如果函数返回false,则您知道解析失败,您可以根据自己的意愿来处理它。Trim()
您的res --尽管您需要将它赋值给一个新变量(例如,var res2 = res.Trim();
)https://codereview.stackexchange.com/questions/57928
复制相似问题