我正在编写一个使用递归解决方案将数字转换为指定基数的程序。我的问题是,屏幕上的输出仅发布了一个数字(我猜这是最后一个数字)。如何正确将余数返回屏幕?
在查看调用堆栈时,一切对我来说都是正确的。我认为我缺少一些非常简单或显而易见的东西。
这是我的程序中调用BaseConverter函数的部分。
while (!File.eof())
{
File >> Decimal;
File >> Base;
// Check if values are valid
// function call BaseConverter (Decimal, Base);
cout << BaseConverter(Decimal, Base) << endl;
}
递归函数将十进制数转换为指定的基数。
int BaseConverter(int Decimal, int Base)
{
// Anchor Point
if (Decimal < Base)
{
return Decimal;
}
// Recursively divides the decimal by the base. Returns the remainder of the Decimal by the base while unwinding.
else
{
return BaseConverter(Decimal / Base, Base) % Base;
}
}
最佳答案
因为您只从函数返回单个整数。
正确的实现:
string ConvertBase(int num, int b) {
if( b < 2 || b > 9 ) throw("Not supported");
stringstream ss;
if(num < b) {
ss << num;
return ss.str();
}
ss << (num % b);
return ConvertBase(num/b, b) + ss.str();
}
请注意,对于大于9的基数,您将需要有字符来表示这些数字。
关于c++ - 递归函数期间C++ Base转换意外输出到屏幕,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39502552/