簡體   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