错误原因:变量i只在for循环中可见,若在循环外使用需要单独定义
1 #include <iostream> 2 using namespace std; 3 4 int main(){ 5 int sum = 0; 6 int n = 5; 7 for(int i = 0 ; i < n ; i++){ 8 sum += i; 9 } 10 cout << i << endl; 11 }
报错
1 #include <iostream> 2 using namespace std; 3 4 int main(){ 5 int sum = 0; 6 int n = 5; 7 int i; 8 for(i = 0 ; i < n ; i++){ 9 sum += i; 10 } 11 cout << i << endl; 12 }
正常运行
参考:
https://www.cnblogs.com/expedition/p/11441388.html
https://wenda.so.com/q/1449244894722638?src=9999&cid-pre=1000204