如何在循环外打印总和?我认为全局变量和局部变量的减速存在一些错误

How do I print the sum outside the loop ? I think there's some mistake in deceleration of global and local variable

当我将第 6 行 (cout << "rank : " << sum + 1 << endl;) 放在循环之外时,它说 sum 未在此范围内声明。 代码就在下面:

#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 << "rank : " << sum + 1 << endl; 循环外?并请说明原因

在 C++ 中,每次花括号打开时,都会创建一个新的作用域,关闭时,它会被销毁。每个作用域都可以访问其他作用域,只要它们没有被销毁。

您的 sum 是在第一个 while 循环的范围内声明的。因此,当 while 循环关闭时,范围被销毁,这导致您声明 sum 为 nullified/destroyed.

您必须在循环之前声明 sum 并且您可能想要初始化它。

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