2016-08-23 9 views
-1
내가 (< < "순위"cout을 < < 합 + 1 < < ENDL) 6 마지막 줄을 넣어

는 합계가 선언되지 않았 음을 말한다 루프 외부 이 범위. 코드는 바로 다음과 같습니다 :루프 외부에서 합계를 인쇄하려면 어떻게해야합니까? 나는 세계 및 지역 변수의 감속에 약간의 실수가 있다고 생각

#include <iostream> 
#include <vector> 
#include <string> 
#include <algorithm> 

using namespace::std; 

int main() { 

string input; 
cout << "Don't enter repetitive alphabet word \n" << "Enter a word : "; 
getline(cin, input); 

vector<char> myVector(input.begin(), input.end()); 
vector<char> myVector2(input.begin(), input.end()); 

sort(myVector2.begin(), myVector2.end()); 

if(myVector2 == myVector){ 
    cout << "rank : 1"; 
} 

else{ 
    for (int i = 0; i < myVector2.size(); i++){ 
     //cout << myVector2[i]; 
    } 

    cout << endl; 

    int q = 0, value = 1, w = 1; 
    while(q < myVector.size()){ 
     int k = 0, temp = 0, sum, value = 1, w = 1; 
     while(k < myVector2.size()){ 
      while(myVector2[k] != myVector[q] && k < myVector2.size()){ 
       while(w < myVector2.size()){ 
        value = value * w ; 
        w++; 
       } 
       k++; 
      } 
      temp = value * (k); 

      break; 
     } 
     sum = sum + temp; 

     myVector2.erase(myVector2.begin()+k); 
    /* for(int j = 0; j < myVector2.size(); j++){ 
      cout << myVector2[j]; 
     }*/ 

     cout << "rank : " << sum + 1 << endl; 
     q++; 
    } 

} 
} 

내가 6 마지막 줄에 인쇄 할 방법 : < < cout을 "순위"< < 합 + 1 < < ENDL을; 루프 바깥에 이 있습니까? 이유를 설명하십시오.

+0

문제는 'sum'이 루프 내에서 선언된다는 것입니다. 선언문을 위로 움직이십시오. – alexeykuzmin0

+0

변수'sum'을 루프 외부에서도 정의 하시겠습니까? –

+0

또한'sum' 변수는 사용하기 전에 초기화되지 않으므로'sum + temp' 할 때 * 동작이 정의되지 않았습니다. –

답변

0

중괄호가 열릴 때마다 새로운 범위가 만들어지고 닫히면 파괴됩니다. 각 범위는 파괴되지 않는 한 다른 범위에 액세스 할 수 있습니다.

합은 제 while 루프의 범위 내에서 선언된다. 그래서 루프가 닫히면 범위가 파괴되어 이라는 선언문의 합이이 무효/파괴됩니다.

루프 앞에 의 합계을 선언해야하며이를 초기화해야 할 수 있습니다.

int q = 0, value = 1, w = 1, sum = 0; 
while(...) { 
    ... 
}