float Calculate(const string &query)
{
std::cout << "Query: " << query << "\n";
unsigned int size = query.length();
char stack[70];
float res;
int m = 0;
for (int i = 0; i < size; i++)
{
if (query[i] >= '0' && query[i] <= '9')
{
stack[m] = query[i] - '0';
m++;
continue;
}
switch (query[i])
{
case '+':
{
res = stack[m - 2] + stack[m - 1];
break;
}
case '-':
{
res = stack[m - 2] - stack[m - 1];
break;
}
case '*':
{
res = stack[m - 2] * stack[m - 1];
break;
}
case '/':
{
res = stack[m - 2]/stack[m - 1];
break;
}
}
stack[m - 2] = res;
m--;
cout << "RES: " << res << "\n";
}
return res;
}
它计算逆波兰表示法。奇怪的函数返回结果
当我打电话给:Calculate("11+")
时,它会返回正确的结果:2
。
但是,当我通过获取RPN串的后一个变量:
string inputStr;
string outputStr;
cout << "Put exercise\n";
getline(std::cin, inputStr);
outputStr = GetRPN(inputStr);
cout << "Output str :" << outputStr << ":\n";
float res = Calculate(outputStr);
std::cout << res << "\n";
所以,当我输入字符串:1+1
,功能GetRPN
回报11+
,我看到,在第二COUT。但结果是0
!
它可能是什么?
string GetRPN(string input)
{
vector <char> operation;
string outputStr; //output string, keep RPN
int stack_count = 0;
for(int i = 0; i < input.length(); i++)
{
if(input[i] >= '0' && input[i] <= '9')
{
outputStr += input[i];
}
else
{
if(operation.empty())
{
operation.push_back(input[i]);
stack_count++;
}
else if(operation[stack_count - 1] == '+' || operation[stack_count - 1] == '-')
{
operation.push_back(input[i]);
stack_count++;
}
else if ((operation[stack_count - 1] == '*' || operation[stack_count - 1] == '/') && (input[i] == '*' || input[i] == '/'))
{
outputStr += operation[stack_count - 1]; // move mark of operation to output str
operation.pop_back(); // delet last element from vector
operation.push_back(input[i]);// plus new operation mark to vector
stack_count++;
}
else if (operation[stack_count - 1] == '*' || operation[stack_count - 1] == '/')
{
outputStr += input[i];
}
}
}
for(int i = operation.size(); i >= 0; i--)
{
outputStr += operation[i]; // move all operation marks to otput str
}
return outputStr;
}
确保您没有任何尾随空格或GetRPN返回的其他“垃圾”空格字符 - 您可能会打印出长度。 – holtavolt 2011-05-24 16:03:37
不知道'GetRPN'是什么,但它可能在字符串outputStr中留下最后的'\ n'或'\ r',这在'switch(query [i])'中不能匹配,只剩下'res'某种程度上为空... – pascal 2011-05-24 16:05:02
你的'Calculate()'看起来不错,并且给定相同的输入应该输出相同的结果。你可以发布你的'GetRPN()'函数吗? – uesp 2011-05-24 16:07:13