0

实现 if 语句时表示向量下标超出范围。我想我在地板上添加了额外的 int,或者在 2D 向量中添加了额外的地板矢量。我正在使用 VS 2010(C++) 我试图在其他问题上找到它但没有成功。

bool is_perfect_square(int);
    int main()
    {
        int cust;
        vector<int>floor;
        vector<vector<int>>hotel;
        floor.push_back(0);
        hotel.push_back(floor);
        hotel[0][0]=1;
        for(cust=2; ; cust++)
        {
            for(int i=0; i<=hotel.size(); i++)
            {
                if(is_perfect_square(cust+hotel[i][floor.size()]))
                {
                    floor.push_back(0);
                    hotel[i][cust]=cust;
                    break;
                }
                else
                {
                    hotel.push_back(floor);
                    hotel[hotel.size()][0]=cust;
                }
            }
        }

        int sum=0;
            for(int a=1; a<=hotel.size(); a++)
            {
                for(int b=1; b<=floor.size(); b++)
                {
                    if(pow(a-1,2)+pow(b-1,2)==14234886498625)
                        sum+=hotel[a-1][b-1];
                }
            }



            cout<<sum<<endl;    
        system("pause");
        return 0;
    }

    bool is_perfect_square(int n)
        {
            int root=floor(sqrt(n));
            return n == root * root;
        }
4

1 回答 1

0

我把我的答案放在评论里。

bool is_perfect_square(int);
int main()
{
    int cust;
    vector<int>floor;
    vector<vector<int>>hotel;
    floor.push_back(0);
    hotel.push_back(floor);
    hotel[0][0]=1;

    // you may not be able to get out of this loop 
    // because the "break" below only exits one level of the loop.
    for(cust=2; ; cust++)
    {
        // this should be changed to "i<hotel.size()", 
        // because the subscript of a vector ranges from 0 to its size minus one.
        for(int i=0; i<=hotel.size(); i++)
        {
            // here "floor.size()" should be floor.size() - 1, the same reason.
            if(is_perfect_square(cust+hotel[i][floor.size()]))
            {
                floor.push_back(0);
                hotel[i][cust]=cust;
                break;
            }
            else
            {
                hotel.push_back(floor);
                hotel[hotel.size()][0]=cust;
            }
        }
    }

    int sum=0;
        for(int a=1; a<=hotel.size(); a++)
        {
            for(int b=1; b<=floor.size(); b++)
            {
                if(pow(a-1,2)+pow(b-1,2)==14234886498625)
                    sum+=hotel[a-1][b-1];
            }
        }



        cout<<sum<<endl;    
    system("pause");
    return 0;
}

bool is_perfect_square(int n)
    {
        int root=floor(sqrt(n));
        return n == root * root;
    }
于 2014-02-11T02:41:07.103 回答