问题是:在第一行给定 Canvas (也就是二维数组)的高度(h)和宽度(w);以及圆心 (x, y) 和半径 (r) 的坐标,打印 Canvas 。如果二维数组的元素在圆圈内,则打印 #
否则打印 .
。下面是我尝试过的,但对于我的生活,我无法弄清楚为什么二维矩阵只包含 .
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
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
最佳答案
原因在这里:*(canvas + i + j)
。
假设 i == 1
和 j == 1
(第二行,第二个元素)。在你的连续数组中,这在位置 1*w + 1
但 *(canvas + i + j)
给你位置 1 + 1
.
因此 i
应该乘以 w
以“跳过”i
行(每行长度 w
) :
*(canvas + i*w + j)
您可以在 ideone 上看到固定的现场演示
关于c - 打印矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42420867/