2017-02-23 11 views
1

問題は次のとおりです。最初の行にキャンバス(つまり2D配列)の高さ(h)と幅(w)を指定すると、円の中心(x、y)と半径(r)の座標でキャンバスを印刷します。 2D配列の要素が円内にある場合は、#を印刷し、それ以外の場合は.を印刷します。私が試したことは以下の通りですが、私の人生ではなぜ2Dマトリックスには.しか含まれていないのか分かりません。 、9、6及び5は、円のX座標(x)がある行列を印刷する

#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)は、Y座標:いくつかの光を投げてください。 (y)および半径(r)):

20 16 
9 6 5 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
.................... 
+0

に固定されたライブデモを見ることができます、h、x、y、rはあなたのコードにありますか?あるいは、これらの値が本当にそこにあるという前提ですか?あなたはそれをプリントのように見せるからです。 –

+2

'*(キャンバス+ i + j)' ----> '*(キャンバス+ j +(i * w))' .... 'i'は行の幅の倍数でなければなりません – LPs

答えて

5

この理由は、*(canvas + i + j)です。

i == 1j == 1(2行目、2番目の要素)とします。隣接する配列では、1*w + 1ではなく*(canvas + i + j)の位置に1 + 1があります。

のでiは、「スキップ」i行(長さwのそれぞれ)にwを掛けする必要があります。

*(canvas + i*w + j)

あなたはwを印刷しないideone

+1

これを書いただけです。私にそれを打つ。 –

+1

私もそうです。私は同じことをコメントしました。 ;)+1 – LPs

+0

ハッピーズ)多分私はそれをより速く読む) –