2013-07-07 170 views
0

我對編程非常陌生,並對for循環中的變量範圍感到疑惑。
我正在試圖做出一些事情,要求用戶輸入一個數字來代表要加在一起的數字量。所以如果他們輸入3,它會一起添加三個數字。for循環中變量的範圍C++

#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',名稱查找。」
這是否意味着我無法訪問該循環之外的變量?有沒有辦法可以改變它,這樣可以讓我呢?
假設原始代碼確實起作用,它確實檢索了nAccum的值,甚至可以保存累積值,或者在for循環結束後它的值完全擦除了嗎?
對不起,這些真正新手的問題,但我無法在其他地方找到答案,並感謝誰決定回答。

+0

外,如果你只是檢查,如果輸入的是否定的,我覺得一個if-else語句應該是足夠的。循環它是矯枉過正 – franklin

回答

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; 
} 
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; 
+0

由於我沒有發生這樣做,我感到非常愚蠢。 –

+0

這裏說的感謝的典型方法是接受/ upvote有用的東西:) –

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; 
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循環