C 简单递归输出调用递归两次
我就是这样试的。主要部分使用C 简单递归输出调用递归两次,c,C,我就是这样试的。主要部分使用fun(9)。所以9不等于或小于1。它调用fun(9/3)两次并打印n,即9。我哪里错了 #include <stdio.h> void fun(int n){ if(n<=1) printf("*"); else{ fun(n/3); fun(n/3); printf("%d",n); } } int main(void){ fun(9); return 0; } #包括 虚无乐趣(int
fun(9)
。所以9不等于或小于1。它调用fun(9/3)
两次并打印n
,即9。我哪里错了
#include <stdio.h>
void fun(int n){
if(n<=1) printf("*");
else{
fun(n/3);
fun(n/3);
printf("%d",n);
}
}
int main(void){
fun(9);
return 0;
}
#包括
虚无乐趣(int n){
如果(n被称为fun(9)
,则显示的代码不会打印**3**39
- 第一个调用具有
n==9
- 因此,如果调用
fun(3)
,则再次调用fun(3)
,然后打印9
- 两个调用中的第一个调用
fun(3)
调用fun(1)
,它打印一个*
,然后再次调用fun(1)
,打印另一个*
,然后打印3
- 两个调用中的第二个调用的作用相同
您的输出应该是
**3**3.9
如果您看不到它是如何工作的,请手动执行,并填写值而不是变量名:
通过1:
void fun(9){ // first pass n=9
if(9<=1) printf("*"); // nope, that's not true
else{
fun(9/3); // call the function again with n = 9/3 = 3
从这里您可以看到,我们将重复pass2逻辑,生成另一个**3
,然后最后一次返回Pass1以打印9
<最后一个输出:<代码> ** 3 ** 39 /代码> /p>请格式化您的代码,看到两个调用“代码>乐趣(n/3);< /Cord>)这不是你所期望的吗?你认为你错在哪里?你期望输出什么?答案回答它输出,339我真的不知道他们怎么得到这样的问题只有一个答案:用户调试器。
void fun(3){ // second pass n=3
if(3<=1) printf("*"); // nope, that's not true
else{
fun(3/3); // call the function again with n = 3/3 = 1
void fun(1){ // third pass n=1
if(1<=1) printf("*"); // yes! so print first *
else{ // this function is only an if and an else, we hit the if
// so it just drops out now
void fun(3){ // second pass n=3 (did this already)
if(3<=1) printf("*"); // nope, that's not true (did this already)
else{
fun(3/3); // call the function with n = 1 (did this already)
fun(3/3); // next recursive call, again with n = 1
void fun(3){ // second pass n=3 (did this already)
if(3<=1) printf("*"); // nope, that's not true (did this already)
else{
fun(3/3); // call the function with n = 1 (did this already)
fun(3/3); // call again with n = 1 (did this already)
printf("%d", 3); // print 3
void fun(9){ // first pass n=9 (did this already)
if(9<=1) printf("*"); // nope, that's not true (did this already)
else{
fun(9/3); // call the function again with n = 3 (did this already)
fun(9/3); // now call the function again with n = 9/3 = 3