c - 如何在 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。
增量具体是如何工作的?谢谢你。
解决方案
预增量运算符 ( ++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
推荐阅读
- mysql - 联合 # 个结果在一起
- android - RealmMigrationNeededException:需要迁移Realm,同时在现有数据库上添加新表,Android
- c# - 如何使用 ConnectedComponents 删除二进制图像中的连接对象
- javascript - Vanilla Javascript:如何使用用户颜色输入在网格上制作多种不同颜色的单元格
- vb.net - 自动增量 Excel OleDb 连接 Vb.net
- python - 如何使用numpy替换数组中的字符?
- android - 没有为片段找到 id 0x7f0800c4 的视图
- python - 如何修复 Pycharm 中的 Python 3 Json 文件错误?
- dns - 咖啡馆 wifi DNS 劫持和 kops 验证集群
- sql - SQL删除多个表中的多行数据