【问题标题】:Output of the program((confused))程序的输出((困惑))
【发布时间】:2013-09-27 02:44:36
【问题描述】:
你能解释一下下面程序的输出吗:
#include <iostream>
using namespace std;
int main()
{
int a=10;
int x=(a++)+(++a)+(a++)+(a++)+(++a);
cout<<x<<endl;
x+= (++a);
cout<<x<<" "<<a<<endl;
}
输出是:
62
78 16
【问题讨论】:
标签:
post-increment
pre-increment
【解决方案1】:
一个很好的例子,说明为什么前增量和后增量并不总是一个好主意。将前后增量依次应用于a (10) 的初始值,您将得到
这一行:
int x=(a++)+(++a)+(a++)+(a++)+(++a);
变成:
x = 10 + 12 + 12 + 13 + 15 // 62
而x+= (++a);变成了
x += 16; // x=78
【解决方案2】:
a++ 在使用 a 的值之后增加 a 的值,而 ++a 在使用它的值之前增加值。
所以在int x = x=(a++)+(++a)+(a++)+(a++)+(++a); 中,第一个 a++ 将使用值 10 并将 a 的值增加到 11,现在下一个 ++a 将 a 的值从 11 增加到值 12,然后使用它。
所以它变成了:
x = 10 + 12 + 12 + 13 + 15 = 62
此时x的值为15。下一个输出可以类似地解释。干杯!