【发布时间】:2012-06-23 19:07:20
【问题描述】:
我刚刚参加了一个 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++。有 1 年的实习经验和 1 年的 C++ 学术经验,但我还没有为其中一些测试做好准备。是否有任何推荐的资源可以让我尝试解决诸如此类的问题以获得更多的“测试”经验?
【问题讨论】:
-
你知道语法吗,比如说数学表达式的BNF语法?
-
寻找大学级别的Introduction编译器课程(和相关书籍/课程材料)。第一个任务应该是构造一个简单的词法分析器/解析器/rec-decent(或类似的)来解析“数学方程”。像这样的简单语法实际上可以通过使用堆栈并在读入时进行处理,因为“没有必要考虑优先级”。无论如何,“不是一个真正的问题”。
-
@K-ballo:BNF 语法太过分了,可能会给你错误的答案,因为上面的问题假定没有优先级,而如果你提取网络语法,它将使用优先级。
-
@Loki Astari:我在 OP 代码中看到了嵌套表达式的括号。但我明白你关于运算符优先级的观点,对。
-
我看不出这个问题如何适合这些类别中的任何一个来获得结束的资格。这显然是一个过于激进的收盘价。 1:您可以说出所要求的内容(1 个代码或伪帮助/2 个推荐资源)。 2:不是
ambiguous, vague, incomplete,因为有一个非常详细的具体问题。这不是修辞,可以在当前论坛中回答,如三个好的答案所示。
标签: c++