C - 函数调用中的前缀和后缀运算符

时间:2017-02-17 15:12:20

标签: c function operators prefix postfix

我知道有类似的问题已被问到,但是在发布我的问题之前我已经阅读了它,它似乎没有帮助我。

以下程序应返回从0到某个数字的总和(i + 1)* 2 +(i + 2)* 3:

#include <stdio.h>
#define MULa 2
#define MULb 3
#define NUM 3

int entry( int a, int b )
{        
    return (a* MULa + b* MULb);
}

int sum(int num)
{
    int my_sum = 0;
    int i = 0, j = 0;

    while (j <= num)
    {
        printf("in iteration %d before incrementing: i is  %d\n", j, i);
        my_sum += entry(i++, i++);
        printf("sum is %d in iteration %d\n", my_sum, j);

        j++;

        printf("after incrementing: i is %d\n", i);
    }
    return (my_sum);
}

int main()
{         
    int my_sum = sum( NUM );
    printf("sum is %d\n", my_sum);
    return 0;
}   

现在,该程序没有按预期执行。

根据我的理解,通过每次迭代,我增加两次,这是在函数调用之后完成的。 我打印出sum的值并预期得到以下结果:

    in iteration 0 before incrementing: i is 0
    sum is 8 in iteration 0     /*(0+1)*2 + (0+2)*3 = 8*/
    after incrementing: value of i is 2
    in iteration 1 before incrementing: i is 2
    sum is 26 in iteration 1     / *8 + (2+1)*2 + (2+2)*3 = 26*
    after incrementing: i is 4
    in iteration 2 before incrementing: i 4
    sum is 54 in iteration 2     /*26+(4+1)*2 + (4+2)*3 = 54*/
    after incrementing: i is 6
    in iteration 3 before incrementing: i 6
    sum is 92 in iteration 3     /*54 + (6+1)*2 + (6+2)*3 = 92*/
    after incrementing: i is 8
    sum is 68

但相反,我得到了这个:

in iteration 0 before incrementing: i 0
sum is 2 in iteration 0
after incremeting: i is 2
in iteration 1 before incrementing: i 2
sum is 14 in iteration 1
after incremeting: i is 4
in iteration 2 before incrementing: i 4
sum is 36 in iteration 2
after incremeting: i is 6
in iteration 3 before incrementing: i 6
sum is 68 in iteration 3
after incremeting: i is 8
sum is 68

我真的不明白为什么这是输出。例如,sum是2,在迭代0中?如果你能解释一下这个功能是如何工作的,那么我很高兴,每一步都会发生什么。

提前致谢!

0 个答案:

没有答案