打印矩阵

bab*_*bon 1 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;
}
Run Code Online (Sandbox Code Playgroud)

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

20 16
9 6 5
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
Run Code Online (Sandbox Code Playgroud)

Yur*_*ych 5

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

假设i == 1j == 1(第二行,第二行).在你的连续数组中,这就像在位置,1*w + 1*(canvas + i + j)给你的位置1 + 1.

所以i应该乘以w"跳过" i行(每个长度w):

*(canvas + i*w + j)

您可以在ideone上看到固定的现场演示