繁体   English   中英

简单C程序及了解output

[英]Simple C program and understanding the output

我下周要参加 C 的考试。 我必须输入,给定 C 程序的 output 是什么。 我们还获得了这些程序的一些示例,以了解要准备什么。 不幸的是,我现在没有太多时间深入研究 C,所以我想做的只是获得一些常识。

所以我有给定的程序:

#include <stdio.h>
int A[] = {1,2,3,5,7,11,13,17,19};
#define MaxJ (sizeof A / sizeof A[0]-1)

int tot(int j)
{
    if (2*j <= MaxJ)
        return tot(2*j) + tot(2*j+1);
    else if (j<=MaxJ)
        return A[j];
    else return 0;
}
int main()
{
    printf("%d", tot(1));
    return 0;
}

问题是,在那个“if”语句中究竟发生了什么? 我知道 MaxJ 是 8 以及为什么,但是 output 60 让我感到困惑。 从我的想法来看,我们将值 1 作为参数传递给 tot(),然后将 1 乘以 2 直到我们得到 16,即 > MaxJ,所以我们将 go 传递给 else if 并返回 A[j],这应该是 19 j = 8。但这是不正确的。

如果您添加一些调试printf ,您可以看到发生了什么:

int A[] = {1,2,3,5,7,11,13,17,19,20,21,22,23,24,25,26,27,28};
#define MaxJ (sizeof A / sizeof A[0]-1)

int tot(int j)
{
    if (2*j <= MaxJ)
    {
        printf(" >>>> j = %d 2*j = %d\n", j, 2*j);
        return tot(2*j) + tot(2*j+1);
    }
    else 
    if (j<=MaxJ)
    {
        printf("j = %d A[j] = %d\n", j, A[j]);
        return A[j];
    }
    else return 0;
}
int main()
{
    printf("MAXJ = %zu\n", MaxJ);
    printf("%d", tot(1));
    return 0;
}

分析它你会发现 function 正在返回上半部分数组元素的总和(如果元素的数量是奇数,那么那一半比下半部分大一)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM