[英]Why does i print a value of 3 in the following code?
The outut of the code below is: 3 2 15
以下代码的输出为:
3 2 15
I was expecting 2 2 15
我期待
2 2 15
Why is this? 为什么是这样?
#include <stdio.h>
int main() {
int a[5] = { 5, 1, 15, 20, 25 };
i = ++a[1];
j = a[1]++;
m = a[i++];
printf("%d %d %d", i, j, m);
return 0;
}
The increment/decrement operators actually change the value of the object, not just return the resulting value. 增量/减量运算符实际上会更改对象的值,而不仅仅是返回结果值。 In the line
m=a[i++];
在行
m=a[i++];
you are incrementing i
again. 你又增加了
i
。
becuase you increment it twice: 因为您将其递增两次:
i=++a[1]; // i = 2
j=a[1]++;
m=a[i++]; // i = 3
printf("%d %d %d",i,j,m);
I want it to help you. 我希望它能为您提供帮助。
#include<stdio.h>
int main()
{
int a[5]={5,1,15,20,25};
i=++a[1]; // i = 2
j=a[1]++; // j = 2
m=a[i++]; // m = 15, i = 3
printf("%d %d %d",i,j,m);
return 0;
}
Code 码
#include <stdio.h>
int main() {
int a[5] = { 5, 1, 15, 20, 25 };
i = ++a[1];
j = a[1]++;
m = a[i++];
printf("%d %d %d", i, j, m);
return 0;
}
Lets go through this step by step.. 让我们逐步进行此操作。
a[1] is 1 a [1]是1
i is ++1 that is.... 2 我是++ 1就是... 2
m is a[i] that is a[2] which is... 15 m是a [i],即a [2],即... 15
After this statement i++ is executed, so 在此语句之后,执行了i ++,因此
after m = 15, m = 15之后
i becomes 3, 我变成3
These values are printed using printf 这些值使用printf打印
Lets proceed step by step: 让我们逐步进行:
#include <stdio.h>
int main() {
int a[5] = { 5, 1, 15, 20, 25 };
i = ++a[1]; // a[1] is incremented, becomes 2, i gets this value 2
j = a[1]++; // j gets a[1] which is 2, then a[1] is incremented and becomes 3
m = a[i++]; // m gets a[2] which is 15, i is incremented and becomes 3
printf("%d %d %d", i, j, m); // prints 3 2 15
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.