我对编程非常陌生,并且想知道 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 循环结束后它的值被完全擦除?
很抱歉这些真正的新手问题,但我无法在其他地方找到答案,感谢决定回答的人。