0

我对编程非常陌生,并且想知道 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' 范围,则名称查找”。
这是否意味着我无法在 for 循环之外访问该变量?有没有办法可以改变它,让它允许我这样做?
假设原始代码确实有效并且确实检索了 nAccum 的值,它甚至会保存累积的值还是在 for 循环结束后它的值被完全擦除?
很抱歉这些真正的新手问题,但我无法在其他地方找到答案,感谢决定回答的人。

4

4 回答 4

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 时,您会犯同样的错误

于 2014-04-05T21:43:35.010 回答
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;
}
于 2013-07-07T04:44:03.283 回答
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;
于 2013-07-07T04:44:11.037 回答
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;
于 2013-07-07T04:49:09.010 回答