for循环C ++中变量的范围

时间:2013-07-07 04:39:47

标签: c++ loops for-loop scope

我对编程非常陌生,并且想知道for循环中变量的范围 我试图制作一些东西,要求用户输入一个代表要加在一起的数字量的数字。因此,如果他们输入3,则会将三个数字加在一起。

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
  int nTarget;
  cout <<"Enter the amount of numbers you wish to add: ";
  cin >> nTarget;
  while (nTarget < 0)
    {
        cout <<"Negative number detected, please enter a positive number: ";
        cin >> nTarget;
    }
    for(int nAccum = 0, nNext, nCounter = 0; nCounter < nTarget; nCounter++)
    {
        cout <<"Enter the number to be added: ";
        cin >> nNext;
        nAccum = (nAccum + nNext)
    }
  cout <<"The total is " << nAccum << endl;

    system("PAUSE");
    return 0;
}

我很抱歉,如果代码难以阅读和草率我只是搞乱了。我的问题是,它给了我一个错误,说“如果'nAccum'的名称查找'因ISO'而改为'范围'。”
这是否意味着我无法在for循环之外访问该变量?有没有办法可以改变它以便它允许我? 让我们说原始代码确实有效,它确实检索了nAccum的值,它是否会保持累积值,或者一旦for循环结束它的值是否被完全删除了?
对于这些真正的新手问题感到抱歉,但我无法在其他地方找到答案,感谢无论谁决定回答。

4 个答案:

答案 0 :(得分:1)

当你在循环中声明任何变量时,它的作用域只在循环内部。 例如:

    for(int i=0; i<3; i++) {
   i=i+2;
}
cout<<i; // here it will give you an error because i is destroyed. outside the loop it doesn't exist.

当你在循环之外训练nAccum时你犯了同样的错误

答案 1 :(得分:0)

nAccum应该作用于函数,而不是循环。在函数顶部定义它(并初始化它),与nTarget相同。

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
  int nTarget;
  int nAccum = 0;
  cout <<"Enter the amount of numbers you wish to add: ";
  cin >> nTarget;
  while (nTarget < 0)
    {
        cout <<"Negative number detected, please enter a positive number: ";
        cin >> nTarget;
    }
    for(int nNext, nCounter = 0; nCounter < nTarget; nCounter++)
    {
        cout <<"Enter the number to be added: ";
        cin >> nNext;
        nAccum = (nAccum + nNext)
    }
  cout <<"The total is " << nAccum << endl;

    system("PAUSE");
    return 0;
}

答案 2 :(得分:0)

如果你想在for循环之外访问nAccum,只需在外面声明它,例如

int nAccum = 0;
for(int nNext, nCounter = 0; nCounter < nTarget; nCounter++)
{
    cout << "Enter the number to be added: ";
    cin >> nNext;
    nAccum = (nAccum + nNext)
}
cout << "The total is " << nAccum << endl;

答案 3 :(得分:0)

如果在for循环外声明的变量nAccum仍将保留for循环中赋给它的值。

int nTarget, nAccum, nNext, nCounter;
cout <<"Enter the amount of numbers you wish to add: ";
cin >> nTarget;
while (nTarget < 0)
{
    cout <<"Negative number detected, please enter a positive number: ";
    cin >> nTarget;
}
for(nAccum = 0, nNext, nCounter = 0; nCounter < nTarget; nCounter++)
{
    cout <<"Enter the number to be added: ";
    cin >> nNext;
    nAccum = (nAccum + nNext)
}
cout <<"The total is " << nAccum << endl;

system("PAUSE");
return 0;