我在这个程序中几乎没有混淆,如果有人可以向我解释此代码和输出的功能,我将获得此程序的输出,例如这样
1
1
2
2
3
3
我想知道两个功能的工作规则,它们如何计算值?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int M(const int n);
int F(const int n)
{
return(n==0)?1:n-M(F(n-1));
}
int M(const int n)
{
return (n==0)?0:n-F(M(n-1));
}
int main()
{
int i;
for(i=0;i<6;i++)
{
printf("%2dn",F(i));
}
printf("n");
return 0;
}
在for
for(i=0;i<6;i++)
{
printf("%2dn",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()
工作方式。F()
中的最后一个命令, return(n==0)?1:n-M(F(n-1));
扩展到
if (n==0){
return 1;
}else{
return n-M(F(n-1));
}
在第一个迭代i:0
中,我们希望 F(0)
为n为零,( n:0
), if (n==0)
为true,执行return 1;
,F(0)
的值必须为1。
对于第二次迭代,我们需要F(1)
,因为if (n==0)
是错误的,而else 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 n-F(M(n-1));
}
M(0) = 0;
M(1)= 1- F(M(0))= 1- F(0) = 1 - 1=0;
现在,我们将其放在F(1) = 1 - M(1)
上,有M(1) = 0;
我们取得了F(1) = 1
。
现在,您的代码输出中的前两对1
是手工计算的。
对于他人,一遍又一遍地做。
,如评论中建议的尝试通过手动跟踪代码,我将与您一起进行前两个迭代,以便您获得IDEA
当您的程序启动时,它将调用您的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
不要沮丧,因为您所要求的实际上会更容易与某些病人一起理解。我非常建议您握住一支笔和纸,然后开始追踪自己。
- 像我一样,按迭代进行迭代。
- 根据条件的正确流量调用每个功能。
- 当您调用函数时,标记您在代码中剩下的位置跳到上述函数,以便一旦返回值,您就会确切地知道将返回值放置在哪里。
纸张的平静,耐心和痕迹。