打印矩阵

时间:2017-02-23 16:12:10

标签: c algorithm multidimensional-array

问题是:给定第一行画布的高度(h)和宽度(w)(换句话说,2D数组);和圆的中心(x,y)和半径(r)的坐标,打印画布。如果2D阵列的元素在圆圈内,则打印#否则打印.。以下是我的尝试,但对于我的生活,我无法弄清楚为什么2D矩阵只包含. s。请点亮一下:

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

typedef struct point {
    int x;
    int y;
} point;

float distance(point p, point q) {
    return sqrt((p.x - q.x)*(p.x - q.x) + (p.y - q.y)*(p.y - q.y));
}

int withinCircle(point circleCentre, point p, int radius) {
    float dist = distance(circleCentre, p);
    if (!(dist > (float) radius)) {
        return 1;
    } else {
        return 0;
    }
}

int main(void){
    point pixel;
    int w, h;
    scanf("%d %d",&w,&h);
    char *canvas = malloc(w * h);

    int circleX, circleY; 
    int r; 
    scanf("%d %d %d",&circleX,&circleY,&r);
    point circleCentre;
    circleCentre.x = circleX; circleCentre.y = circleY;

    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            pixel.x = j; pixel.y = i;
            if (withinCircle(circleCentre, pixel, r)) {
                *(canvas + i + j) = '#';
            } else {
                *(canvas + i + j) = '.';
            }
        }
    }

    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
              printf("%c", *(canvas + i + j));
        }
        printf("\n");
    }

    return 0;
}

输出(20和16分别是宽度(w)和高度(h).9,6和5分别是圆的X坐标(x),Y坐标(y)和半径(r) ):

20 16
9 6 5
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................

1 个答案:

答案 0 :(得分:5)

原因在于:*(canvas + i + j)

假设i == 1j == 1(第二行,第二行)。在您的连续数组中,这位于1*w + 1位置,但*(canvas + i + j)会为您提供位置1 + 1

所以i应该乘以w到&#39;跳过&#39; i行(每个长度为w):

*(canvas + i*w + j)

您可以在ideone

上看到固定的现场演示