将用户输入的int解析为不工作C++的数字
这是一个将用户输入的int解析为数字的函数。我对返回向量的函数进行递归调用。我检查直到数字的值变为零。但当我运行它时,它进入了一个无限循环 有什么问题吗?这里基本上有两个循环,一个是递归循环,一个是while循环 递归调用是正确的,但您不应将条件置于一段时间内。 这就是无限循环出现的地方。在检查n是否为的过程中!=0,但该正文中未修改n。你应该:将用户输入的int解析为不工作C++的数字,c++,recursion,vector,C++,Recursion,Vector,这是一个将用户输入的int解析为数字的函数。我对返回向量的函数进行递归调用。我检查直到数字的值变为零。但当我运行它时,它进入了一个无限循环 有什么问题吗?这里基本上有两个循环,一个是递归循环,一个是while循环 递归调用是正确的,但您不应将条件置于一段时间内。 这就是无限循环出现的地方。在检查n是否为的过程中!=0,但该正文中未修改n。你应该: vector<int> vec(unsigned int n) { vector<int> num; whi
vector<int> vec(unsigned int n)
{
vector<int> num;
while (n != 0)
{
num.push_back(n%10);
vec(n / 10);
}
return num;
}
在代码中,您没有在第vecn/10行存储递归调用的值。如果您正在执行递归,则不需要在while循环中放置。您只需要做一件事:递归或循环 以下是您可能要尝试的代码: 循环:
在没有意义的地方使用递归。旁白:用户的条目以数字形式开始。避免忘记用户输入的内容可能比复制更容易。
if (n != 0)
{
num.push....
vec(n/10);
}
return num;
vector<int> vec(unsigned int n)
{
vector<int> ans;
while(n!=0)
{
ans.push_back(n%10);
n=n/10;
}
reverse(ans.begin(),ans.end());
return ans;
}
vector<int> vec1(unsigned int n)
{
vector<int> ans;
if(n==0)
return ans;
ans.push_back(n%10);
vector<int> tmp=vec1(n/10);
ans.insert(ans.end(),tmp.begin(),tmp.end());
return ans;
}
vector<int> vec(unsigned n)
{
vector<int> ans=vec1(n);
reverse(ans.begin(),ans.end());
return ans;
}