首页 > 解决方案 > 如何在 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。请提供答案。

标签: c++

解决方案


您的变量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;
}

推荐阅读