首页 > 解决方案 > 如何在 C 中增加数组中的元素(整数)?

问题描述

int main(){
    int a[5]= {5, 1, 15, 20, 25};
    int i, j, k=1, m;
    i = ++a[1]; // i becomes a[1] + 1 which is 2 but a[1] changes to 2 even though I'm assigning a value to i?
    j = a[1]++; // j becomes a[1]+1 which is 2+1 but stay as 2? 
    m = a[i++]; // because i is 2, shouldn't the output be a[3]? 

    printf("\n%d %d %d", i, j, m);
    return 0;
}

在此代码中,输出为 3、2、15。

增量具体是如何工作的?谢谢你。

标签: carraysincrementpost-incrementpre-increment

解决方案


预增量运算符 ( ++x) 增加值并返回新值。后增量运算符 ( x++) 增加值并返回旧值

如果将前自增和后自增运算符分解为两条不同的行,很容易看出会发生什么。

int a[5]= {5, 1, 15, 20, 25};
int i, j, k=1, m;

// i = ++a[1]; becomes:
++a[1];    // a = {5, 2, 15, 20, 25}
i = a[1];  // i = 2

// j = a[1]++; becomes:
j = a[1];  // j = 2
a[1]++;    // a = {5, 3, 15, 20, 25}

// m = a[i++]; becomes:
m = a[i];  // m = a[2] = 15
i++;       // i = 3

所以,最后:

i = 3
j = 2
m = 15

特别是,在这种情况下:

m = a[i++];

该变量i先前的值为2,因此增量运算符递增i(变为3),但返回2,因此该行等效于:

m = a[i];  // Use old value here
i++;       // Increment after

推荐阅读