我是编程新手,在练习一些问题时我遇到了一段 C 代码。
void count(int n)
{
static int d = 1;
printf("%d ", n);
printf("%d ", d);
d++;
if(n > 1) count(n-1);
printf("%d ", d);
}
int main()
{
count(3);
}
Output:
3 1 2 2 1 3 4 4 4
谁能解释一下为什么输出不是我期望的 3 1 2 2 1 3 4 。 我尝试用 java 编写这段代码,但输出与我的预期相差甚远
public static void main (String[] args)
{
count(3);
}
static void count(int n){
int d = 1;
System.out.print(n+" ");
System.out.print(d+" ");
d++;
if(n>1)count(n-1);
System.out.print(d+" ");
}
Output:
3 1 2 1 1 1 2 2 2
关于函数和方法调用过程,我有什么遗漏的吗?
最佳答案
在C
中,静态
变量在函数调用期间保留其值。
通过上下文,您可以看到调用 count(3)
时会发生什么。
count(3)
prints: 3 1
count(2)
prints: 2 2
count(1)
prints: 1 3 4
count(2)
prints: 4
count(3)
prints: 4
您错过了最后两个4
,因为您忘记了:
once `count(1)` returns `count(2)` prints the value of `d` once more, and
once `count(2)` returns `count(3)` prints the value of `d` once more
现在,对于您的 java
代码,它并不等同于 C
代码,因为 d
不是静态成员。您可以通过将 d
设为静态成员来使其与您的 C
代码类似。
/* ... Some code ...*/
static int d = 1;
public static void main (String[] args)
{
count(3);
}
static void count(int n){
// Remove this line
/*int d = 1;*/
/* ... same code ...*/
/* ... same code ...*/
}
此java
代码应该给出与您的C
代码相同的结果。
关于java - 这两个代码的输出是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38285475/