我剛剛參加了以下問題的研究生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語法是過度殺傷性的,可能會給你錯誤的答案,因爲上面的問題假定沒有優先順序,而如果你拉出網絡語法,它將使用優先級。 –