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

时间:2016-07-09 19:19:15

标签: java c

我是编程新手,在练习一些问题时,我遇到了C语言中的代码。

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 

任何人都可以向我解释为什么输出不是我预期的3 1 2 2 1 3 4。 我尝试在java中编写这段代码,输出甚至没有达到我的预期

<input id="uploadFile" type="file" />

关于函数和方法调用过程,我有什么遗漏。

4 个答案:

答案 0 :(得分:3)

Cstatic变量保留其在函数调用中的值。

在上下文中,您可以看到调用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不是静态成员。您可以通过将C设为静态成员来使其与d代码类似。

/* ... 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代码给出相同的结果。

答案 1 :(得分:1)

这是您的代码所做的,逐行:

使用单个参数n

声明void函数计数
void count(int n)
{

将{d}声明为static:这意味着它将通过函数调用保持不变。如果增加一个静态变量,函数返回并再次调用该函数,静态变量将保持递增。

   static int d = 1;

打印参数和静态变量d

   printf("%d ", n);
   printf("%d ", d);

增量d(LOOK OUT:这意味着如果我们再次调用count(),我们将在下一行中执行,d将不等于1,而是等于2)

   d++;

如果n大于1,则使用n - 1作为参数调用计数

   if(n > 1) count(n-1);

打印d

   printf("%d ", d);
}

所以,这就是它的作用:

  • count()被调用n为3
  • n(3)已打印
  • d(1)已打印
  • d增加1,现在为2
  • n(3)大于1
  • 使用2作为参数调用
  • count()
  • n(2)已打印
  • d(2)已打印
  • d(2)增加1,现在为3
  • n(2)大于1
  • count()以1作为参数调用
  • n(1)已打印
  • d(3)已打印
  • d增加1,现在为4
  • n等于一个
  • d(4)打印
  • 您可能已经注意到我们三次调用count(),并且没有时间完成两次。
  • 检查n > 1是否正在打印d
  • 后留下的唯一声明
  • 我们现在必须做两次
  • d(4)打印
  • d(4)打印

答案 2 :(得分:0)

作为注释中已经提到的weather Vane,递归会导致此输出。如果你想要你的expectet结果我认为这应该有助于你的c代码:

void count(int n) {

    static int d = 1;
    printf("%d ", n);
    printf("%d ", d);
    d++;
    if (n > 1)
    {
        count(n - 1);
    }
    else
    {
        printf("%d ", d);
    }
}

int main()
{
    int b = 0;
        count(3);

}

答案 3 :(得分:0)

C方法在函数中使用静态变量,这在Java中无法完成。静态变量在第一次调用函数时初始化,然后仅在以后的函数调用中更新。 Java没有这样的概念,但是,以下内容也是如此:

private static int d=1;

public static void main (String[] args) 
{
    count(3);
}

static void count(int n){
    System.out.print(n+" ");
    System.out.print(d+" ");
    d++;
    if(n>1)count(n-1);
    System.out.print(d+" ");

}