下周我要考C。我將不得不輸入給定 C 程式的輸出是什么。我們還得到了這些程式的一些示例,以了解要準備什么。不幸的是,我現在沒有太多時間深入研究 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 以及為什么,但輸出 60 讓我感到困惑。從我的想法來看,我們將值 1 作為引數傳遞給 tot(),然后將 1 乘以 2 直到我們得到 16,即 > MaxJ 所以我們轉到 else if 并回傳 A[j],這應該是 19 j = 8. 但這是不正確的。
uj5u.com熱心網友回復:
如果您添加一些 debug printfs,您可以看到發生了什么:
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;
}
分析它你會發現該函式正在回傳上半部分陣列元素的總和(如果元素數是奇數,則該一半比下半部分大一)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/363019.html
標籤:C
上一篇:在C中修改結構內的變數
下一篇:如何減少此C程式的令牌數量
