首页 > 解决方案 > Bullseye matrix draw

问题描述

I hope you can help me with this question. So i want to create a matrix which design looks like a target, filling the borders of the square or the matrix with 1 and after a concentric square of 0, another concentric square with 1 and on and on after you select the dimension of the square matrix(if i scan 3, the matrix will be a 3x3) The problem is with the concentric 1s, i dont know the condition to print them. Can you help me? I should look like this: Image

This is what i have done till now

#include <stdio.h>
void rellenarMatrizdiana(int filas, int cols,int diana[cols][cols]);
int main()
{
    int diana[500][500], tdiana;
    printf("Selecciona el tamaño de la diana: ");
    scanf("%d", &tdiana);
    rellenarMatrizdiana(tdiana,tdiana,diana);
}
void rellenarMatrizdiana(int filas, int cols,int diana[cols][cols]){


    for(int f=0; f<filas; f++){
        for(int c=0; c<cols; c++){

            if (f==0||f==filas-1||c==0||c==cols-1){
                diana[f][c]=1;

            }else{
                diana[f][c]=0;
            }

            printf("%d\t", diana[f][c]);

        }
        printf("\n");
    }
}

标签: c

解决方案


#include <stdio.h>
#include <string.h>
#define FILLED 'X'

void printDiag(int N) {
    if(N<0) N *= N;
    //unsigned char (*tri)[N] = (unsigned char(*)[N])calloc(N*N, 1);
    unsigned char tri[N][N];
    memset(&tri, 0, sizeof(tri)); // "variable-sized object may not be initialized"

    for(int j=0; j<N; j+=2) {
        for(int i=j; i<N-j; i++) tri[j][i] = tri[i][j] = tri[N-1-j][N-1-i] = tri[N-1-i][N-1-j] = FILLED;
    }

    for(int r=0; r<N; r++) { // print triangle
        for(int c=0; c<N; c++) printf("%c", tri[r][c]);
        printf("\n");
    }   

    //free(tri);
}

int main(void) {
    for(int n=0; n<=12; n++) {
        printf("N=%i:\n", n);
        printDiag(n);
        printf("\n");
    }

    return 0;
}

这是方法。只需翻译并实施您的确切要求,即可更好地了解该程序。

输出:

N=0:

N=1:
X

N=2:
XX
XX

N=3:
XXX
X X
XXX

N=4:
XXXX
X  X
X  X
XXXX

N=5:
XXXXX
X   X
X X X
X   X
XXXXX

N=6:
XXXXXX
X    X
X XX X
X XX X
X    X
XXXXXX

N=7:
XXXXXXX
X     X
X XXX X
X X X X
X XXX X
X     X
XXXXXXX

N=8:
XXXXXXXX
X      X
X XXXX X
X X  X X
X X  X X
X XXXX X
X      X
XXXXXXXX

N=9:
XXXXXXXXX
X       X
X XXXXX X
X X   X X
X X X X X
X X   X X
X XXXXX X
X       X
XXXXXXXXX

N=10:
XXXXXXXXXX
X        X
X XXXXXX X
X X    X X
X X XX X X
X X XX X X
X X    X X
X XXXXXX X
X        X
XXXXXXXXXX

N=11:
XXXXXXXXXXX
X         X
X XXXXXXX X
X X     X X
X X XXX X X
X X X X X X
X X XXX X X
X X     X X
X XXXXXXX X
X         X
XXXXXXXXXXX

N=12:
XXXXXXXXXXXX
X          X
X XXXXXXXX X
X X      X X
X X XXXX X X
X X X  X X X
X X X  X X X
X X XXXX X X
X X      X X
X XXXXXXXX X
X          X
XXXXXXXXXXXX

推荐阅读