了解递归十进制二进制代码? [英] understanding recursive decimal to binary code?
问题描述
我正在研究一个可以将数字转换为二进制格式的程序.
I'm working on a program that can convert number to its binary form.
在帮助下,我能够得到此消息,并且它似乎可以工作,但我只是不了解如何操作.我想做到这一点的最好方法是尝试解释我认为这是如何工作的,并且有人可以纠正我.
With help, I was able to get this, and it seems to work but I just don't understand how. I guess the best way to do this is to try to explain how I think this is working and someone can correct me.
我有一个具有if语句的函数,该语句说明如果n除以2不等于0,然后除以2.然后,如果n/2则输出余数,即1或0.
I have a function that has an if statement that says if n divided by 2 isn't equal to 0 then divide n by 2. Then it prints the remainder if n /2 so either 1 or 0.
main函数仅使用我给它的任何数字(在本例中为456)运行该函数.
The main function just runs the function with whatever number I give it, in this case 456.
但是程序如何知道多次运行该函数以获取整个二进制形式?
But how does the program know to run the function multiple times to get the entire binary form?
我觉得这并不复杂,但我不明白.
I feel like this isn't that complicated but I'm not getting it.
#include <stdio.h>
void ConvertToBinary(int n)
{
if (n / 2 != 0) {
ConvertToBinary(n / 2);
}
printf("%d", n % 2);
}
int main (){
ConvertToBinary (456);
return 0;
}
推荐答案
函数ConvertToBinary
是递归的,这意味着它可以自我调用.在某个时候,函数需要知道何时停止调用自身.这就是所谓的基本情况.
The function ConvertToBinary
is recursive, meaning it calls itself. At some point the function needs to know when to stop calling itself. This is called the base case.
在第一次调用此函数时,n = 456.在这种情况下,n/2 != 0
是true,因此函数这次用228进行调用.它一直在自行调用,直到传递了其中n/2 != 0
为false的值(这是基本情况)为止.然后,对函数的最内层调用将显示n % 2
并返回.下一个最里面的调用还将为n
的值显示n % 2
,依此类推,直到调用堆栈.
On the first call to this function, n=456. In this case n/2 != 0
is true, so the function calls itself, this time with 228. It keeps calling itself until it gets passed a value where n/2 != 0
is false, which is the base case. The innermost call to the function then prints n % 2
and returns. The next innermost call also prints n % 2
for its value of n
, and so on up the call stack.
所以函数调用看起来像这样:
So the function calls look something like this:
ConvertToBinary(456)
ConvertToBinary(456/2=228)
ConvertToBinary(228/2=114)
ConvertToBinary(114/2=57)
ConvertToBinary(57/2=28)
ConvertToBinary(28/2=14)
ConvertToBinary(14/2=7)
ConvertToBinary(7/2=3)
ConvertToBinary(3/2=1)
print 1%2=1
print 3%2=1
print 7%2=1
print 14%2=0
print 28%2=0
print 57%2=1
print 114%2=0
print 228%2=0
print 456%2=0
结果:
111001000
这篇关于了解递归十进制二进制代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!