java - 这两个代码的输出是什么?

标签 java c

我是编程新手,在练习一些问题时我遇到了一段 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/

相关文章:

c - C 和/或 Objective-C 中的组头文件

Java 8 Optional 如何处理太多 orElses

java - JDBC 在我的 postgres 查询中将表大写

java - WSDL 客户端调用失败

c - 为什么 main 函数总是加载在同一个地址,而变量大多数时候有不同的地址?

c - 解析参数

java - 如何在字符串数组的特定索引处追加字符串

java - 在 gitlab-ci 中运行 selenium 测试用例时出现 chrome 无法访问错误。似乎 headless chrome 存在一些问题,任何人都可以帮忙解决这个问题

c - 为什么这个投影矩阵不起作用?

c - 我从日志中收到一条消息,上面写着 : Error: request for member "height" in something not a structure or union