📜  门| GATE-CS-2007 |第 85 题

📅  最后修改于: 2021-09-26 04:24:30             🧑  作者: Mango

考虑以下 C函数,输出是什么?

#include 
int f(int n)
{
    static int r = 0;
    if (n <= 0) return 1;
    if (n > 3)
    {
        r = n;
        return f(n-2)+2;
    }
    return f(n-1)+r;
}
  
int main()
{
    printf("%d", f(5));
}

(一) 5
(乙) 7
(三) 9
(四) 18答案: (D)
解释:

f(5) = f(3)+2  
The line "r = n" changes value of r to 5.  Since r 
is static, its value is shared be all subsequence 
calls.  Also, all subsequent calls don't change r
because the statement "r = n" is in a if condition 
with n > 3.

f(3) = f(2)+5
f(2) = f(1)+5
f(1) = f(0)+5
f(0) = 1

So f(5) = 1+5+5+5+2 = 18 

这个问题的测验