这个程序的工作规则是什么,解释?
我很想在这个程序中混淆,我想如果有人能向我解释这个代码和输出的function,我得到这个程序的输出这样
1 1 2 2 3 3
我想知道这两个函数的工作规则如何计算值?
#include #include #include int M(const int n); int F(const int n) { return(n==0)?1:nM(F(n-1)); } int M(const int n) { return (n==0)?0:nF(M(n-1)); } int main() { int i; for(i=0;i<6;i++) { printf("%2d\n",F(i)); } printf("\n"); return 0; }
考虑一下
for(i=0;i<6;i++) { printf("%2d\n",F(i)); }
简短回答:
F(0) => 1;
F(1)=> 1 - M(F(0))
when F(0):1 then F(1) = 1 - M(1) go to calculate M(1), but we start from 0, M(0)= 0; M(1) = 1- F(M(0)) = 1- F(0) = 1-1=0; last we have M(1) = 0; and as F(1) = 1-M(1) = 1-0=1 last we have: F(1)=1
更完整:
让我们看看F()
的工作方式。 return(n==0)?1:nM(F(n-1));
F()
的最后一个命令, return(n==0)?1:nM(F(n-1));
扩展到
if (n==0){ return 1; }else{ return nM(F(n-1)); }
在迭代i:0
第一个中,我们希望F(0)
为n为零,( n:0
), if (n==0)
为真, return 1;
执行, F(0)
值必须为1。
对于第二次迭代,我们想要F(1)
,因为if (n==0)
为假,则执行block。
现在n:1
, F(1) = 1 - M (F(0))
。
在前一次迭代中,我们得到F(0)=1
,好了,现在我们可以重新连接或等式: F(1) = 1 - M(1)
,很明显,如果我们简单地得到M(1)
值,就把它放到最后一个公式F(1)
已经解决了。
为此,我们必须扩展M()
函数。
同样,我们可以写M()
。
if (n==0){ return 0; }else{ return nF(M(n-1)); }
M(0) = 0;
M(1)= 1- F(M(0))= 1- F(0) = 1 - 1=0;
现在我们有M(1) = 0;
把它放在F(1) = 1 - M(1)
我们得到F(1) = 1
。
现在,您手动计算代码输出中的前两对1
。
对于其他人,一遍又一遍地这样做。
正如评论中所建议的那样,尝试手动跟踪代码,我将与您一起完成前两次迭代,以便您了解相关信息
程序启动时,它调用main
函数,并开始执行for循环,如下所示:
i=0 => calls F(n=0) => is n==0 true? Yes => return 1 => print 1 i=1 => calls F(n=1) => is n==0 true? No => then 1-M(F(0)) => F(0) calculated from the previous iteration to return a value of 1 => call M(n=1) => is n==0 true? No => then 1-F(M(0)) => M(0) returns 0 since n==0 is true => then 1-F(M(0)) is equal to 1-F(0) => we calculated F(0) to return 1 => so 1-F(0) return 0 from M => take the return back to 1-M(F(0)) => 1-0 = 1 => print 1
不要感到沮丧,因为你问的问题对某些病人来说实际上要容易理解。 我特别建议您按住笔和纸并开始跟踪自己。
- 像我一样迭代迭代。
- 根据if条件的正确流程调用每个函数。
- 当你调用一个函数时,在代码中标记你要跳转到所述函数的位置,这样一旦它返回一个值,你就知道返回值的确切位置。
和平的纸张,耐心和痕迹。