为什么在for循环中更改变量后变量不会更改?
这是我的代码
#include <iostream>
int main()
{
int j = 1;
for (int i=0, j=1; i<10; i++)
{
std::cout << j << std::endl;
j++;
}
std::cout << j << std::endl;
return 0;
}
这是我的输出:
2
3
4
5
6
7
8
9
10
11
1
我只想知道为什么 j 的值没有改变
回答
你有两个变量j:
int j = 1; // 1st "j" here
for (int i=0, j=1; i<10; i++) // 2nd "j" here
您正在j循环中修改 2nd并在循环j后打印 1st 。
- @Jeffrey I think it should simply be `for (int i=0; i<10; i++)` in this case because `j` is already initialized to `1` at the declaration.