递归函数是否反向打印? [英] Does recursive function print in reverse?

查看:38
本文介绍了递归函数是否反向打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>

using namespace std;
void convertToBinary(unsigned int n)
{
    if (n>0)
    {
        convertToBinary(n / 2);
        cout << n % 2;
    }
}
int main(){
    unsigned int n;
    cin >> n;
    convertToBinary(n);

}

这是一个从十进制转换为二进制的函数递归,例如如果我给这个函数 n 等于 10 输出是 1010, How come 1 is at最右边的数字?它将是 0 因为 10 % 2 = 0,然后打印 0 ,所以预期的输出将是 101,因为有一个 >0.

Here is a function recursion that coverts from decimal to binary, for example If I give this function n equals to 10 the output is 1010, How come 1 is at the rightmost digit? It would be 0 since 10 % 2 = 0, then print 0 , so the expected output would be 101, since there's leading a 0.

推荐答案

递归调用使用的数据结构称为 堆栈.其工作原理是后进先出.因此,除非满足您的基本条件,即 (n > 0)convertToBinary 才会在打印 n%2 本身之前递归调用.当基本条件不满足时,convertToBinary 由于堆栈结构而开始反向打印二进制值.

The data structure used by recursive calls is called as stack. Its working principle is last-in-first-out. So, not until your base condition i.e. (n > 0) is satisfied, convertToBinary re-cursively call before printing n%2 itself. When the base condition isn't fulfilled, convertToBinary commences to print binary values inversely because of stack structure.

这篇关于递归函数是否反向打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆