您是否有任何想法自动随机地将括号添加到数学运算字符串?
例如。
给定的操作字符串:
57 x 40 - 14 + 84 ÷ 19
我需要在上面的字符串中随机自动添加括号。
所以它变成:
(57 x 40) - 14 + (84 ÷ 19) 或
(57 x 40) - (14 + 84 ÷ 19) 或
57 x (40 - 14) + (84 ÷ 19) 或
57 x (40 - 14 + 84 ÷ 19) 或
57 x (40 - (14 + 84) ÷ 19)
非常感谢您的帮助!
米克
您是否有任何想法自动随机地将括号添加到数学运算字符串?
例如。
给定的操作字符串:
57 x 40 - 14 + 84 ÷ 19
我需要在上面的字符串中随机自动添加括号。
所以它变成:
(57 x 40) - 14 + (84 ÷ 19) 或
(57 x 40) - (14 + 84 ÷ 19) 或
57 x (40 - 14) + (84 ÷ 19) 或
57 x (40 - 14 + 84 ÷ 19) 或
57 x (40 - (14 + 84) ÷ 19)
非常感谢您的帮助!
米克
我假设了三件事:
C# 中的示例:
Math m = new Math();
string p = m.DoStuff("57 x 40 - 14 + 84 ÷ 19");
Console.WriteLine(p);
class Math
{
internal string DoStuff(string p)
{
bool isParOpen = false;
Random rnd = new Random();
StringBuilder result = new StringBuilder();
int i;
string[] stack = p.Split(' ');
foreach (var item in stack)
{
if (int.TryParse(item, out i))
{
if (rnd.Next(2) == 1)
{
result.Append(isParOpen ? string.Format("{0}) ", item) : string.Format("({0} ", item));
isParOpen = !isParOpen;
}
else
{
result.Append(item).Append(" ");
}
}
else
{
result.Append(item).Append(" ");
}
}
if (isParOpen)
{
result.Append(")");
}
return result.ToString();
}
}
如果您将数学表达式作为字符串处理,您可以随机添加括号(例如,将随机字符添加到字符串),然后使用脚本引擎,您可以评估表达式。