如何在C++中反转输出顺序?(有或没有递归)
How do I reverse the order of output in C++? ( With or without recursion)
我的任务是编写一个程序,输出十进制整数的二进制表示。例如,它使用十进制13,其中所需的输出为1101。
我的问题是,我的程序中的两个函数都没有按正确的顺序打印这个数字。他们都按所需顺序倒排打印。
int binaryRecursion(int decimalInteger) //This function uses recursion
{
int remainder = decimalInteger % 2;
cout << remainder;
if ( decimalInteger / 2 == 0 )
{
cout << endl;
}else{
return binaryRecursion(decimalInteger / 2);
}
return 1;
}
void binaryNormal(int decimalInteger) //This function does NOT use recursion
{
while (decimalInteger != 0)
{
int remainder = decimalInteger % 2;
cout << remainder;
decimalInteger /= 2;
}
}
int main()
{
int decimalInteger;
cout << "Enter your decimal integer." << endl;
cin >> decimalInteger;
binaryRecursion(decimalInteger);
binaryNormal(decimalInteger);
return 0;
}
不要直接输出它,而是将它放在一个不断增长的std::string
中,最终将其反转。
我相信这应该能奏效:
void binaryRecursion(int decimalInteger) //This function uses recursion
{
int remainder = decimalInteger % 2;
if ( decimalInteger / 2 != 0 )
{
binaryRecursion(decimalInteger / 2);
}
cout << remainder;
}
您可以将其存储在string
中并输出相反的结果:
void binaryNormal(int decimalInteger) //This function does NOT use recursion
{
string buff = "";
while (decimalInteger != 0)
{
int remainder = decimalInteger % 2;
buff += remainder + '0';
decimalInteger /= 2;
}
for(int i = buff.length() - 1; i >= 0; cout << buff[i--]);
cout << endl;
}
或者,您可以对递归函数执行此操作(如果您不太关心endl
):
void binaryRecursion(int decimalInteger) //This function uses recursion
{
int remainder = decimalInteger % 2;
if (decimalInteger / 2 > 0) binaryRecursion(decimalInteger / 2);
cout << remainder;
}
下面是一个工作示例
相关文章:
- 如何在C++中递归地按相反顺序打印集合
- 递归函数的执行顺序
- 了解递归函数的执行顺序
- 编写一个递归功能,该功能采用数组并以相反顺序显示元素,而无需在末尾启动数组的索引
- 如何创建跟踪以显示存在递归的调用顺序
- 递归C++字母顺序函数重复返回相同的值
- OpenMP:即使在深度极限的情况下,递归任务也比顺序慢
- 使用递归的顺序二叉树遍历与使用堆栈的优缺点
- 使用递归的顺序和预序遍历 - 二叉搜索树 C++
- 正十进制整数的递归函数位数,按c++的相反顺序排列
- 如何通过递归反转字符串中单词的顺序
- 通过模板函数重载以正向顺序进行模板递归(关于std::tuple上的迭代)
- C++递归函数,可反转数组索引在两个边界之间的顺序
- 无法使用非递归顺序方法遍历二叉树
- C++在递归函数中平衡了树/调用顺序
- 通过递归以相反的顺序打印出一行中的单词
- 递归:按顺序遍历返回列表
- 了解按相反顺序打印数组的递归解决方案
- 使用递归的BST顺序遍历
- 我想要一个递归函数来检查使用二进制搜索数组的顺序