c - 打印矩阵

标签 c algorithm multidimensional-array

问题是:在第一行给定 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 == 1j == 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/

相关文章:

multidimensional-array - 是否有一个 Rust ndarray 等价于切片上的 numpy 算术?

c - 我如何将它变成一个结构?

c++ - [文字游戏]Quiddler Solver Algorithm

c - 从控制台的特定位置获取输入

c# - 实现递归哈希算法

algorithm - 是否有一个好的整数线光栅化算法?

java - 如何有效地在 SWT/Swing 表中填充数百万条记录

php - 这一行正在覆盖数组

c - 指针运算 (char*) &a[1] - (char *)&a[0] == 4

c - 解决迷宫回溯