为什么是 2 和 -2 而不是 1 和 -1
Why 2 and -2 instead of 1 and -1?
本文关键字:为什么 更新时间:2023-10-16
我写了这个非常简单的程序:
#include <iostream>
using namespace std;
int main()
{
int x = 0;
cout << x++<<endl;
cout<<++x<<endl;
int y = 0;
cout<<y--<<endl;
cout<<--y<<endl;
return 0;
}
这是我运行它时得到的:
0
2
0
-2
我使用code::blocks来编写程序,我的操作系统是Ubuntu 12.10。我应该如何修复我的程序,以便我看到 0 1 0 -1?
您需要了解后递增(递减)和前递增(递减)的概念。
员额增量
cout << x++<<endl;
您可以将此行理解为"返回 x 的值"+"递增 x 的值"。即返回值在增量之前。
因此,返回 0 并将 x 的值增加到 1。
预递增
cout<<++x<<endl;
这是相反的 - 返回递增的值。
因此,将 x 的值增加到 2 并返回 2。
cout << x++ << endl;
后增量从 0 递增到 1 x
,并生成旧值 0。x
的值现在为 1。
cout << ++x << endl;
预递增从 1 递增到 2 x
,并生成新值 2。x
的值现在为 2。
x++
会使你的变量为 1,但由于 after++ 行为,到那时++x
将是 2
"for"循环中的后递增和预递增产生相同的输出
X++ 首先打印它,然后递增该值。++X 首先递增该值,然后打印它。
所以
cout<<x++<<endl // Prints '0' and increments to '1'
cout<<++x<<endl // Increments '1' to '2' and prints it
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 为什么在全局范围内使用"extern int a"似乎不行?
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 为什么会发生堆损坏
- 为什么使用 "this" 指针调用派生成员函数?
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么比较运算符如此快速
- 为什么 Serial.println(<char[]>);返回随机字符?
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 为什么不;名字在地图上是按顺序排列的吗
- 我的字符计数代码计算错误.为什么
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 为什么 std::unique 不调用 std::sort?
- 既然存在危险,为什么项目要使用-I include开关
- 为什么在运行时没有向我们提供有关分段错误的更多信息?