简体   繁体   English

螺旋矩阵在最后一个“for”循环中中断并且不显示任何内容

[英]spiral matrix breaks on the last "for" loop and doesn't show anything

#include<iostream>
using namespace std;

int main()
{
    int n;
    cout<<"Enter the size of the array :";
    cin>>n;                                
    int A[n][n];
    int y=n,k=1,p=0,i;    



while(k<=n*n)                      
{
    for(i=p;i < y;i++)     
    {
        A[y-1][i]=k++;
    }
    for(i=y - 2;i > p;i--)      
    {
        A[i][y-1]=k++;
    }
    for(i=y - 2;i > p;i--)         
    {
        A[p][i]=k++;
    }
    for(i = p + 1;i < y; i++)      
    {
        A[i][p]=k++;
    }
    p++;
    y--;

}
if(!n%2)                      
{
    A[(n+1)/2][(n+1)/2]=n*n; 
}
for(i=0;i<n;i++)             
{
    for(int j=0;j<n;j++)
    {
        cout<<A[i][j]<<"\t";
    }
    cout<<endl;
}
return 0;

I need to do a spiral matrix the way like this > enter image description here .我需要像这样做一个螺旋矩阵>在此处输入图像描述 It breaks on the last "for" cycle and just doesn't show anything;;;它在最后一个“for”循环中断,只是不显示任何内容;;; Still, it shows up if I'm replacing one of the loop's statements;;尽管如此,如果我要替换循环语句之一,它就会显示出来;; I would be grateful if you point me where's my mistake!如果您指出我的错误在哪里,我将不胜感激!

(this code is a modified one brought from here https://www.includehelp.com/cpp-programs/print-a-spiral-matrix.aspx ) (此代码是从这里带来的修改代码https://www.includehelp.com/cpp-programs/print-a-spiral-matrix.aspx

There were simply some little mistakes on the bounds of the loops (the bounds of the spiral).只是在循环的边界(螺旋的边界)上有一些小错误。 Here is a slightly modified programme.这是一个稍微修改的程序。

PS: Note that you should avoid to use VMA int A[n][n] which is C, not C++. PS:请注意,您应该避免使用 VMA int A[n][n]这是 C,而不是 C++。

#include<iostream>
//using namespace std;

int main()
{
    int n;
    std::cout << "Enter the size of the array :";
    std::cin >> n;                                
    int A[n][n];
    int y = n, k = 1,p = 0,i;    

    while(k<= n*n)                      
    {
        for(i=p;i < y;i++)     
        {
            A[y-1][i]=k++;
        }
        for(i=y - 2;i >= p;i--)      
        {
            A[i][y-1]=k++;
        }
        for(i = y - 2;i >= p;i--)         
        {
            A[p][i]=k++;
        }
        for(i = p + 1;i < y-1; i++)      
        {
            A[i][p]=k++;
        }
        p++;
        y--;

    }
    if(!n%2)                      
    {
        A[(n+1)/2][(n+1)/2]=n*n; 
    }
    for(i=0;i<n;i++)             
    {
        for(int j=0;j<n;j++)
        {
            std::cout<<A[i][j]<<"\t";
        }
        std::cout << "\n";
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM