我一直在写代码,一个计算器,用递归工作。
输入:!+ 1 3
代码将执行1+3,然后取和
的余量输出:"24">
我写完了基本代码(还没有过滤掉错误的用户输入),当我构建它时,它没有显示任何警告,但是一旦我运行它,我就会抛出'std::out_of_range'警告。我试了一下,把问题归结为一个功能,但我无法确定到底是哪里出了问题。
//Calculation
string Rechner::berechne(vector <string> t) //Calculator::calculate
{
for (unsigned int i = t.size() - 1; i >= 0; i--) //searches the vector starting from the back
{
if( t.at(i) == "+" || t.at(i) == "*" || t.at(i) == "!") //finds the last operator
{
t.at(i) = differenziere(i, t); //switches out the last operator with
//the result of the operation (differenziere(i, t)
if ( t.at(i) == "!")
{
t.pop_back(); // delets last element of vector and
berechne(t); // searches for the next Operator
}
else
{
t.pop_back(); //delets last two elements
t.pop_back();
berechne(t); //searches for next operator
}
}
}
return t.at(0); //when there is no more operator left, this returns the Result of the whole operation
}
例如输入:5输出应该是5,因为没有更多的操作符,但是我得到了out_of_range警告。
输入:+ 1具有与警告相同的输出。
所以我最好的猜测是,一旦向量由一个字符串组成,由于某种原因,它属于if函数,这对我来说没有意义。
Input是一个字符串,我将其转换为一个向量。这一切都很好,我已经测试了。
我正在使用code::blocks, c++11和windows笔记本电脑。
我希望你能帮助我。请原谅我的英语,这不是我的母语。我通常会说流利的英语,但我没有很长时间谈论编码的话题,所以这对我来说有点不同。i >= 0
总是为真,因为i
是无符号的。
而不是
for (unsigned int i = t.size() - 1; i >= 0; i--) //searches the vector starting from the back
{
你可以做
for (unsigned int i_loop = t.size(); i_loop > 0; i_loop--) //searches the vector starting from the back
{
unsigned int i = i_loop - 1; // i_loop is positive here thanks to the loop condition