我刚刚参加了以下问题的研究生C++开发人员的测试。它没有做得太好,因为我无法确定完成任务的明确方式。时间限制也没有帮助。我感兴趣的是如何经验的开发人员会解决后续问题 - 伪或示例代码:评估一个简单的字符串数学表达式
Evaluate
Write a function in C or C++ that evaluates the result of a simple expression.
The function should ignore whitespace, but stop at the first non valid character.
Valid tokens are listed in the table below:
0-9 - Only integers are allowed in expressions
() - Nested expressions should be evaluated first.
+, -, *,/- Basic operators are addition, subtraction, multiplication and division.
The expression should be parsed from left to right. It is not necessary to consider operator precedence in your solution (e.g. 1 + 3 * 4 = 16). If there is an error in the expression, the function should return false.
Suggested prototype for function:
Example:
bool evaluate(const char *expression, int &result)
{
...
}
**Input**
1+3
(1 + (12 * 2)
**Result**
4
N/A
**Return code**
true
false (missing bracket)
此外,这是第二个C++,我已经未能成功完成。使用C++已经有1年的跨学科经验和1年的学术经验,但我没有准备好进行这些测试。有没有推荐的资源可以帮助我解决诸如此类问题,以获得更多的“测试”体验?
你知道_grammars_,例如说在_BNF grammar_的数学表达式? –
寻找一个大学水平的*介绍*编译课程(和相关书籍/课程材料)。第一个任务之一应该是构造一个简单的词法分析器/解析/ rec-decent(或类似的)来解析“数学方程式”。这样一个简单的语法实际上可以通过使用堆栈和读取时的处理来“踢”,因为“没有必要考虑优先级”。无论如何,“不是真正的问题”。 – 2012-06-23 19:24:31
@ K-ballo:BNF语法是过度杀伤性的,可能会给你错误的答案,因为上面的问题假定没有优先顺序,而如果你拉出网络语法,它将使用优先级。 –