问题
#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);
}
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
.
回答1:
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.
来源:https://stackoverflow.com/questions/50083724/does-recursive-function-print-in-reverse