c++ - 如何在 while 循环之外使用在 while 循环中声明的变量?
问题描述
#include"std_lib_facilities.h"
int main()
{
int i = 0;
int x = i + 2;
while(i<10){
++i;
}
cout<<x<<'\n';
}
我是初学者,我希望打印结果:在每个循环之后,我应该增加 1,但问题是如果我们打印 x,它仍然是 2。请提供答案。
解决方案
您的变量i
已经增加,但问题是,x
之前已经分配了 0 + 2 (i + 2) 并且稍后执行了循环,因此值没有改变。考虑以下代码:
#include <iostream>
int main(void)
{
int i = 0;
int x;
for (; i < 10; i++) // same algorithm as per of your requirement in FOR loop
{
x = i + 2;
std::cout << x << std::endl; // x will be incremented each time
}
return 0;
}
推荐阅读
- javascript - TypeError : ...map 不是函数 - react.js
- r - 从行到前的最后两个非 NA 观测值
- c# - 如何在不知道完整电子邮件地址的情况下从下拉菜单中选择第一个电子邮件地址?
- git - Git sqash 和 rebase 工作流,带有一个 staging 和 master 分支
- c - 不使用库函数查找字符串长度
- ios - Xamarin Forms iOS listview 的单元格自动调整其内容(来自 url 的图像)
- angular - Angular中的动态表来自两个对象数组
- python - 无法使用 Python 解压缩下载的文件 - Sentinel 卫星数据
- vb.net - vb.net 如何使用 movelast 或 movenext?
- javascript - Plugin/Preset 文件不允许导出对象,只有在 ReactJs 中使用 jest 时才起作用