一個函式evaluateCountdown,它接受一個包含用逆波蘭表示法撰寫的數學運算式的字串,并以雙精度形式回傳運算式的計算結果。
在逆波蘭表示法 (RPN) 中,運算子寫在它們所作用的物件之后而不是它們之間。例如:
3.0 4.0
與通常的(中綴)符號 (3.0 4.0) 相同。或以下RPN格式的運算式:
3.0 4.0 2.0 *
是相同的 (3.0 4.0) * 2
我收到一個邏輯錯誤,輸入"3.0 4.0 - 2.0 *"應該給出輸出-2.0但是我在調??用主函式時收到的輸出是0,輸入字串必須是數字為雙倍的格式,當輸入字串為,例如,"3 4 - 2 *"(回傳 的正確答案-2),但不是在形式"3.0 4.0 - 2.0 *"
該函式evaluateCountdown遍歷輸入字串,當它找到一個數字時,它將該數字作為雙精度數推入堆疊,例如 when tokens[i]is 3then 3 tokens[i 1] tokens[i 2],在這種情況下'3' '.' '0'作為雙精度數推入堆疊。然而,這并沒有發生,我不知道為什么。
#include <string>
#include <sstream>
#include <vector>
#include <stack>
#include <iostream>
#include <iterator>
using std::vector;
using std::ostream;
using std::string;
using std::cout;
using std::stack;
using std::iterator;
using std::endl;
using std::stod;
double evaluateCountdown(string & tokens) {
// this method does not work if the string is empty or a string of just spaces, string must be a expression in RPN
stack<double> stack;
for (int i = 0; i < tokens.size(); i ) {
if (tokens[i] == ' ')
{
double val1 = stack.top();
stack.pop();
double val2 = stack.top();
stack.pop();
stack.push((val1 val2));
}
else if (tokens[i] == '-')
{
double val1 = stack.top();
stack.pop();
double val2 = stack.top();
stack.pop();
stack.push((val2 - val1));
}
else if (tokens[i] == '*')
{
double val1 = stack.top();
stack.pop();
double val2 = stack.top();
stack.pop();
stack.push(val1 * val2);
}
else if (tokens[i] == '/')
{
double val1 = stack.top();
stack.pop();
double val2 = stack.top();
stack.pop();
stack.push((val2 / val1));
}
else if (tokens[i] == ' ')
{
// if char is a space do nothing and move onto the next char.
}
else
{
string str = "";
char c1, c2, c3;
c1 = tokens[i];
c2 = tokens[i 1];
c3 = tokens[i 2];
// concat chars togther to get required string eg '3' '.' '0'
auto ans = string(1, c1) c2 c3;
str = ans;
double val = stod(str);
stack.push(val);
}
}
double val = stack.top();
stack.pop();
return val;
}
int main() {
string s = "3.0 4.0 - 2.0 *";
double ans = evaluateCountdown(s);
cout << ans << endl;
}
uj5u.com熱心網友回復:
當代碼找到一個數字時,它應該增加i2,除非這樣做代碼不起作用。
因此,else條件可以寫成如下(else陳述句的其余部分將保持不變):
c1 = tokens[i];
c2 = tokens[ i];
c3 = tokens[ i];
如果你是一個新的程式員,我建議你在遇到這樣的問題時,使用除錯器來除錯你的程式(即使是最專業的程式員也需要除錯他們的代碼)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/349115.html
標籤:C 11
