2017-02-23 69 views
1

问题是:给定第一行上画布(换句话说,二维数组)的高度(h)和宽度(w);并且中心(x,y)和圆的半径(r)的坐标将打印画布。如果二维数组的元素在圆圈内,则打印#,否则打印.。下面是我尝试过的,但对于我的生活,我无法弄清楚为什么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 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
+0

一个固定的现场演示,你在哪里打印传单W ,你的代码中的h,x,y和r?或者这只是一个假设,这些价值真的在那里?因为你让它看起来像印刷品。 –

+2

'*(canvas + i + j)'---->'*(canvas + j +(i * w))'....'i'必须是行宽的倍数 – LPs

回答

5

原因是这样的:*(canvas + i + j)

假设i == 1j == 1(第二行,第二个元素)。在您的连续阵列中,位置为1*w + 1,但是*(canvas + i + j)会为您提供位置1 + 1

所以i应该由w相乘, '跳过' i行(每个长度w的):

*(canvas + i*w + j)

你可以看到ideone

+1

只是想写这个。打败了我。 –

+1

我也是。我评论说同样的。 ;)+1 – LPs

+0

会发生)也许我只是读得更快) –