按功能跟踪代码

时间:2016-08-03 15:01:36

标签: c

我知道答案是a = 0,b = 10和c = 2,因为我把它写出并编译了,但我不确定答案是如何找到的。

#include <stdio.h>

int f(int a, int b)
{
    int c;

    c=3*a-b;
    a=(c+17)%23;
    b=23%(a+5);

    return a-b+c;
}

int main()
{
    int a=7, b=3, c=2;

    a=f(c,b);
    b=f(a,c);
    printf("a=%d,b=%d,c=%d\n", a,b,c);

    return 0;
}

2 个答案:

答案 0 :(得分:2)

让我们逐行 -

a = f(c,b) -

c = 3 * a - b --> (3 * 2) - 3 = 3
a = (c+17) % 23 --> 20 % 23 = 20
b = 23 % (a+5) --> 23 % 25 = 23

return a - b + c --> 20 - 23 + 3 = 0

a = 0

b = f(a,c) -

c = 3 * a - b --> (3 * 0) - 2 = -2
a = (c+17) % 23 --> (-2 + 17) % 23 = 15
b = 23 % (a+5) --> 23 % 20 = 3

return a - b + c --> 15 - 3 + -2 = 10

b = 10

c值保持2

答案 1 :(得分:0)

代码充满了重新分配和多余的初始化,这使代码难以理解。如果我们像这样重写它,计算将更容易理解:

#include <stdio.h>

int f(int a, int b)
{
    const int c = 3 * a - b;
    const int d = (c + 17) % 23;
    const int e = 23 % (d + 5);

    return c + d - e;
}

int main(void)
{
    const int c = 2;
    const int a = f(c, 3);
    const int b = f(a, c);

    printf("a=%d,b=%d,c=%d\n", a, b, c);
    return 0;
}