生成C中所有n位的字符串 [英] generate all the strings of n bits in C

查看:148
本文介绍了生成C中所有n位的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void binary(int n)



{



if(n< 1)

printf(%s \ n,A); //假设A是一个全局变量



else



{



A [n-1] ='0';



二进制(n-1);



A [n-1] ='1';



二进制(n-1);



}



}

任何人都能解释如何为n = 2生成堆栈帧吗? = 2我只得到00和11,但剩下的数字是10和01是如何生成的?

void binary(int n)

{

if(n < 1)
printf("%s\n",A); // Assume A is a global variable

else

{

A[n-1] = '0';

binary(n-1);

A[n-1] = '1';

binary(n-1);

}

}
Can anyone explain how the stack frames are generated for n=2?when n=2 i am getting only 00 and 11 but how are the remaining numbers i.e 10 and 01 generated?

推荐答案

请看我对这个问题的评论。



我基本上回答了关于堆栈的问题;还会添加这个:函数参数放在堆栈上,当函数返回时它们随框架消失。但是当然,你需要认真学习堆栈,堆栈帧和调用是如何工作的,这是编程的最基本的基础之一。但是你的问题没有为研究它提供足够的样本,除了工作递归,所以没有别的事情可以解释。



参见:< a href =https://en.wikipedia.org/wiki/Call_stack> https://en.wikipedia.org/wiki/Call_stack [ ^ ]。



现在,你真正的问题是你不要甚至尝试使用 n 的值。



你需要解决的问题是按位运算符和循环:

https://en.wikipedia.org/ wiki / Bitwise_operations_in_C [ ^ ],

http://www.cprogramming.com/tutorial/bitwise_operators.html [ ^ ]。



-SA
Please see my comment to the question.

I basically answered you about stack; will also add this: a function parameters are put on the stack, and they disappear with the frame when function returns. But of course, you need to learn seriously how stack, stack frames and calls work, this is one of the most fundamental basics of programming. But your question does not provide any adequate sample for the study of it, except the work "recursion", so there is nothing else to explain.

See also: https://en.wikipedia.org/wiki/Call_stack[^].

Now, your real problem is that you don't even try to use the value of n.

All you need to solve your problem is bitwise operators, and a loop:
https://en.wikipedia.org/wiki/Bitwise_operations_in_C[^],
http://www.cprogramming.com/tutorial/bitwise_operators.html[^].

—SA


如果你不明白你的代码是做什么的,那么最好是看看它用调试器做什么

调试器允许您逐步执行代码并在代码执行时检查变量。

您将看到代码未按预期执行的位置和原因。


游览代码片段不完整,我们无法编译它以查看它在做什么以及它失败的原因。
If you don't understand what is doing your code, the best is to see what it is doing with a debugger.
The debugger allow you to execute your code step by step and inspect variable as the code is executed.
You will see where and why your code is not doing what you expect.

Tour code fragment is not complete and we can't compile it to see what it is doing and why it fail.


这篇关于生成C中所有n位的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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